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


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的遷移。

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM