第一步:新建类:RoutingModule
using System; using System.Web; using System.Text; namespace HttpFiles { public class RoutingModule : IHttpModule { public void Dispose() { } public void Init(HttpApplication context) { //注册自定义请求时间 context.BeginRequest += new EventHandler(context_myRequest); } void context_myRequest(object sender, EventArgs e) { HttpApplication ap = sender as HttpApplication; HttpContextBase context = new HttpContextWrapper(ap.Context); this.context_doRequest(context); } public virtual void context_doRequest(HttpContextBase context) { //获取请求头中的Authorization Base64加密后的用户名和密码 String authorization = HttpContext.Current.Request.Headers["authorization"]; //验证用户和密码 if (!string.IsNullOrEmpty(authorization)) { string[] authorizationString = authorization.Split(' '); if (authorizationString.Length == 2) { String base64String = authorizationString[1]; String accountString = Base64Util.Base64Decode(Encoding.UTF8, base64String); //获取服务端用户名和密码进行作对比,此处写法简单用于测试,正式应用可以与数据库进行交互进行验证 string userpass = System.Configuration.ConfigurationManager.AppSettings.Get("authUser"); if (accountString == userpass) { return; } } } //未认证则返回401登录认证界面 HttpContext.Current.Response.StatusCode = 401; HttpContext.Current.Response.Status = "401 未认证的请求"; HttpContext.Current.Response.AddHeader("WWW-Authenticate", "Basic realm="STOP!""); HttpContext.Current.Response.End(); } } /// <summary> /// 第二种方法:使用自定义http handler /// </summary> public class myhandler : IHttpHandler { public void ProcessRequest(HttpContext context) { string FileName = context.Server.MapPath(context.Request.FilePath); if (context.Request.UrlReferrer == null || context.Request.UrlReferrer.Host == null) { context.Response.ContentType = "image/JPEG"; context.Response.WriteFile("~/no.gif"); } else { if (context.Request.UrlReferrer != null && (context.Request.UrlReferrer.Host.IndexOf("localhost") > -1)) { context.Response.ContentType = "image/JPEG"; context.Response.WriteFile(FileName); } else { context.Response.ContentType = "image/JPEG"; context.Response.WriteFile("~/no.gif"); } } } public bool IsReusable { get { return true; } } public myhandler() { } } }
第二步:添加组件的注册引用,把上边创建的列,添加进去
效果查看