2016-12-12 76 views
2

在asp.net 4.0,我們可以使用以http模塊工作重寫模塊像這樣ASP.Net MVC:如何通過重寫URL的中間件在ASP.NET核心

protected void Application_BeginRequest(Object sender, EventArgs e) 
{ 
    string CountryCodeInUrl = "", redirectUrl=""; 
    var countryCode = CookieSettings.ReadCookie(); 
    if (countryCode=="") 
    { 
     countryCode = "gb"; 
    } 

    if (HttpContext.Current.Request.RawUrl.Length >= 2) 
    { 
     CountryCodeInUrl = HttpContext.Current.Request.RawUrl.Substring(1, 2); 
    } 

    if (countryCode != CountryCodeInUrl) 
    { 
     if (HttpContext.Current.Request.RawUrl.Length >= 2) 
     { 
      if (HttpContext.Current.Request.RawUrl.Substring(1, 2) != "") 
      { 
       countryCode = HttpContext.Current.Request.RawUrl.Substring(1, 2); 
      } 
     } 
     if(!System.Web.HttpContext.Current.Request.RawUrl.Contains(countryCode)) 
     { 
      redirectUrl = string.Format("/{0}{1}", countryCode, System.Web.HttpContext.Current.Request.RawUrl); 
     } 
     else 
     { 
      redirectUrl = System.Web.HttpContext.Current.Request.RawUrl; 
     } 
     CookieSettings.SaveCookie(countryCode); 
     System.Web.HttpContext.Current.Response.RedirectPermanent(redirectUrl); 
    } 
} 

現在告訴我,我怎麼可能ASP.NET Core中的中間件重寫上面的代碼?

我剛纔讀這篇文章部分https://docs.microsoft.com/en-us/aspnet/core/migration/http-modules

請指導我詳細。謝謝

回答

2

你幾乎只需要將代碼移到中間件類中,並使用Core HttpContext而不是System.Web。

這樣一類是這樣的:

//RedirectMiddleware.cs

public class RedirectMiddleware 
{ 
    private readonly RequestDelegate _next; 

    public RedirectMiddleware(RequestDelegate next) 
    { 
     _next = next; 
    } 

    public async Task Invoke(HttpContext context) 
    { 
     string CountryCodeInUrl = "", redirectUrl = ""; 
     var countryCode = CookieSettings.ReadCookie(); 
     if (countryCode == "") 
     { 
      countryCode = "gb"; 
     } 

     if (context.Request.Path.Value.Length >= 2) 
     { 
      CountryCodeInUrl = context.Request.Path.Value.Substring(1, 2); 
     } 

     if (countryCode != CountryCodeInUrl) 
     { 
      if (context.Request.Path.Value.Length >= 2) 
      { 
       if (context.Request.Path.Value.Substring(1, 2) != "") 
       { 
        countryCode = context.Request.Path.Value.Substring(1, 2); 
       } 
      } 
      if (!context.Request.Path.Value.Contains(countryCode)) 
      { 
       redirectUrl = string.Format("/{0}{1}", countryCode, context.Request.Path.Value); 
      } 
      else 
      { 
       redirectUrl = context.Request.Path.Value; 
      } 
      CookieSettings.SaveCookie(countryCode); 
      context.Response.Redirect(redirectUrl, true); 
     } 

     await _next.Invoke(context); 
    } 
} 

要使用它,那麼你在你Startup.cs文件進行註冊,在註冊MVC中間件之前,像這樣:

app.UseMiddleware<RedirectMiddleware>(); 

app.UseMvc(routes => 
{ 
    routes.MapRoute(
     name: "default", 
     template: "{controller=Home}/{action=Index}/{id?}"); 
}); 

我希望這將讓您一開始,你可以看到this博客張貼於中間件的更多信息。

+0

它不會重定向頁面應該重定向,但它不移動 – 1AmirJalali