ASP.NET WebAPI框架解析第二篇(HttpModule的创建和使用)

2021-03-14 09:28

阅读:408

namespace WebHost.HttpModules
{
     public class AuthorizeHttpModule : IHttpModule
     {
         public void Dispose()
         {
             return;
         }

        public void Init(HttpApplication context)
         {
             //此时HttpContext还未构建完成,不能在这里操作HttpContext
             //注册事件监听函数
             context.BeginRequest += Authorize;
         }
         private void Authorize(object sender,EventArgs e)
         {
             HttpApplication app = sender as HttpApplication;

            if (app.Request.Headers.Get("name") != "HK")
             {
                 //不加这一行客户端可能不能自动正确的解析字符编码
                 app.Response.Headers.Add("content-Type", "text/html;charset=utf-8");
                 //通过Write(string s)写入的字符串在内部默认被转换为utf-8编码。C#string默认编码为UTF-16
                 //要先写入原始的字符串编码,调用BinaryWrite(byte[] bytes)
                 app.Response.Write("验证不通过!");
                 app.CompleteRequest();
             }
         }
     }
}


评论


亲,登录后才可以留言!