如何將IHttpHandler和IHttpModule遷移到ASP.NET Core中間件

  • 2021 年 2 月 26 日
  • 筆記

ASP.NET Core是一個跨平台、開源的框架,用於在Windows、Mac和Linux作業系統(OS)上開發web應用程式。你可以使用以下任何IDE開發ASP.NET Core 應用程式:

  • Visual Studio
  • Visual Studio for Mac
  • Visual Studio Code

在這篇博文中,我們將學習如何如何將asp.net IHttpHandler和IHttpModule遷移到ASP.NET Core中間件並提供程式碼示例。

讓我們開始吧!

ASP.NET IHttpHandler

在ASP.NET應用程式中,HTTP處理程式是一個進程,它在對向web伺服器的每個響應上執行。我們可以創建自己的自定義HTTP處理程式。

下面是將所有.aspx頁重定向到一個新頁的程式碼。

public class RedirectionHandler : IHttpHandler
{
 public bool IsReusable
 {
 get { return false; }
  }
 public void ProcessRequest(HttpContext context)
 {
 var response = context.Response;
    response.Write("<p>Process files with .aspx extension</p>");
 // Any redirection logic can be written here.
 }
}

web.config中添加如下程式碼:

<add name="RedirectionHandler" verb="*" path="*.aspx" type="MyWebApplication.RedirectionHandler" resourceType="Unspecified"/>

ASP.NET IHTTPModule

IHttpModule還將在應用程式的每個請求的HTTP處理程式執行之前和之後。它們幫助我們驗證傳入和傳出的請求並修改它們。

下面是用於根據用戶的IP地址限制用戶的IHttpModule程式碼。

public class IPRestrictionModule : IHttpModule
{
 public void Init(HttpApplication context)
 {
 context.BeginRequest += (source, arguments) =>
 {
 var application = (HttpApplication)source;
 var beginContext = application.Context;
 beginContext.Response.Write("<p>Restrict Users based on IP</p>");

 // Code logic comes here.
 };

 context.EndRequest += (source, arguments) =>
 {
 var application = (HttpApplication)source;
 var endContext = application.Context;
 endContext.Response.Write("<p>Request ended.</p>");
 };
 }
}

web.config中添加如下程式碼:

<add name="RestrictionModule" type=" MyWebApplication.IPRestrictionModule" />

ASP.NET Core中間件

在ASP.NET Core應用程式中,中間件組件將替換IHttpHandler和IHttpModule。它是針對每個請求執行的組件。我們可以使用IApplicationBuilder介面在Startup類的Configure方法中添加中間件。

可以使用以下四種方法:

Run

終止HTTP管道。

Use

將中間件添加到請求管道。

Map

根據請求路徑匹配請求委託

MapWhen

支援基於謂詞的中間件分支。

讓我們看看如何將ASP.NET IHttpHandler和IHttpModule遷移到ASP.NET Core中間件!

將 IHttpHandler遷移到ASP.NET Core中間件

1. 使用如下程式碼創建RedirectionHandlerMiddleware 類​​​​​​​

public class RedirectionHandlerMiddleware
{
 private RequestDelegate _next;
 public RedirectionHandlerMiddleware(RequestDelegate next)
 {
    _next = next;
  }
 public async Task Invoke(HttpContext context)
 {
    await context.Response.WriteAsync("<p>Process files with .aspx extension</p>");
 // Any Redirection logic can be return here.
 }
}

2. 在ApplicationBuilder中創建一個擴展方法,以在請求管道中使用RedirectionHandlerMiddleware。

3. 然後,為擴展方法創建一個名為MiddlewareExtension的類,並在其中使用以下程式碼。​​​​​​​

public static class MiddlewareExtension     
{
     public static IApplicationBuilder UseRedirectionHanlderMiddleware
                   (this IApplicationBuilder applicationBuilder)
     {
         return applicationBuilder.UseMiddleware<RedirectionHandlerMiddleware>();
     }
}

4. 我們需要在Startup.cs文件中包含下一個程式碼。

app.MapWhen(context => context.Request.Path.ToString().EndsWith(".aspx"),
        appBuilder => {
            appBuilder.UseRedirectionHanlderMiddleware();
         });

​​​​​​​現在,我們已經完成了IHttpHandler的遷移。

將 IHttpModule遷移到ASP.NET Core中間件

1. 使用如下程式碼創建IPRestrictionModuleMiddleware類。​​​​​​​

public class IPRestrictionModuleMiddleware 
{
       private RequestDelegate _next;
       public IPRestrictionModuleMiddleware (RequestDelegate next)
       {
           _next = next;
       }
       public async Task Invoke(HttpContext context)
       {
            await context.Response.WriteAsync("<p>Begin request</p>");
            await _next.Invoke(context);
            await context.Response.WriteAsync("<p>End request</p>");
       }
 }

2. 與之前一樣,我們需要添加一個擴展方法用來在請求管道中添加中間件。

3. 然後,向現有的MiddlewareExtension類中添加以下程式碼:​​​​​​​

public static class MiddlewareExtensions        
{
    public static IApplicationBuilder UseRedirectionHanlderMiddleware
           (this IApplicationBuilder applicationBuilder)
    {
        return applicationBuilder.UseMiddleware<RedirectionHandlerMiddleware>();
    }
         
    public static IApplicationBuilder UseIPRestrictionModuleMiddleware
           (this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<IPRestrictionModuleMiddleware>();
    }
}

4. 然後,將中間件包含在Startup.cs文件中。​​​​​​​

// For Module
app.UseIPRestrictionModuleMiddleware();
 
 // For Handler
app.MapWhen(context => context.Request.Path.ToString().EndsWith(".aspx"),
        appBuilder => {
                appBuilder.UseRedirectionHanlderMiddleware();
         });

這樣,我們就完成了對IHttpModule的遷移。

原文鏈接://www.syncfusion.com/blogs/post/how-to-migrate-asp-net-http-handlers-and-modules-to-asp-net-core-middleware.aspx

Tags: