諾禾致源、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();
});
}
在如上代碼片段中我們有一些中間件的添加,同時也有中間件的次第。

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