诺禾致源、ASP.NET Core中间件与HttpModule有何不同

ASP.NET Core中间件与HttpModule有何不同
前言
在ASP.NET Core中最大的更改之一是对Http恳求管道的更改,在ASP.NET中我们理解HttpHandler和HttpModule但是到如今这些曾经被交换为中间件那么下面我们来看一下他们的不同处。

HttpHandler
Handlers处置基于扩展的特定恳求,HttpHandlers作为停止运转,同时做到对ASP.NET响应恳求。他是一个完成System.Web.IHttphandler接口的类。任何完成IHttpHandler接口的类都能够作为Http恳求处置响应的目的程序。
它提供了对文件特定的扩展名处置传入恳求,
ASP.NET框架提供了一些默许的Http处置程序,最常见的处置程序是处置.aspx文件。下面提供了一些默许的处置程序。

Handler Extension Description
Page Handler .aspx handle normal WebPages
User Control Handler .ascx handle Web user control pages
Web Service Handler .asmx handle Web service pages
Trace Handler trace.axd handle trace functionality
创立一个自定义HttpHandler

public class CustomHttpHandler:IHttpHandler
{

public bool IsReusable
{
    //指定能否能够重用途理程序
    get {return true;}
}

public void ProcessRequest(HttpContext context)
{
    //TODO
    throw new NotImplementedException();
}

}
在web.config中添加配置项

<system.web>



</system.web>

<system.webServer>



</system.webServer>
异步HttpHandlers
异步的话需求继承HttpTaskAsyncHandler类,HttpTaskAsyncHandler类完成了IHttpTaskAsyncHandler和IHttpHandler接口

public class CustomHttpHandlerAsync:HttpTaskAsyncHandler
{

public override Task ProcessRequestAsync(HttpContext context)
{
    throw new NotImplementedException();
}

}
HttpModule
下面是来自MSDN

Modules are called before and after the handler executes. Modules enable developers to intercept, participate in, or modify each individual request. Modules implement the IHttpModule interface, which is located in the System.Web namespace.

HttpModule相似过滤器,它是一个基于事情的,在应用程序发起到完毕的整个生命周期中访问事情

自定义一个HttpModule
public class CustomModule : IHttpModule
{
public void Dispose()
{
throw new NotImplementedException();
}
public void Init(HttpApplication context)
{
context.BeginRequest += new EventHandler(BeginRequest);
context.EndRequest += new EventHandler(EndRequest);
}
void BeginRequest(object sender, EventArgs e)
{
((HttpApplication)sender).Context.Response.Write(“恳求处置前”);
}
void EndRequest(object sender, EventArgs e)
{
((HttpApplication)sender).Context.Response.Write(“恳求处置完毕后”);
}
}
web.config中配置

<system.web>



</system.web>

<system.webServer>



</system.webServer>
中间件
中间件能够视为集成到Http恳求管道中的小型应用程序组件,它是ASP.NET中HttpModule和HttpHandler的分离,它能够处置身份考证、日志恳求记载等。

中间件和HttpModule的类似处
中间件和HttpMoudle都是能够处置每个恳求,同时能够配置停止返回我们本人的定义。

中间件和httpModule之间的区别
HttpModule 中间件
经过web.config或global.asax配置 在Startup文件中添加中间件
执行次第无法控制,由于模块次第主要是基于应用程序生命周期事情 能够控制执行内容和执行次第依照添加次第执行。
恳求和响应执行次第坚持不变 响应中间件次第与恳求次第相反
HttpModules能够附件特定应用程序事情的代码 中间件独立于这些事情
中间件示例
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
在如上代码片段中我们有一些中间件的添加,同时也有中间件的次第。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章