【问题标题】:ASP.Net MVC:How to rewrite url by middleware in ASP.NET CoreASP.Net MVC:如何在 ASP.NET Core 中通过中间件重写 url
【发布时间】:2017-04-27 09:12:07
【问题描述】:

在 asp.net 4.0 中,我们可以使用 http 模块来重写模块,如下所示:

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

【问题讨论】:

    标签: c# asp.net-core-mvc httpmodule


    【解决方案1】:

    您几乎只需将代码移至中间件类,并使用 Core HttpContext 而不是 System.Web 。

    这样的类应该是这样的:

    //重定向中间件.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 博客文章以了解有关中间件的更多信息。

    【讨论】:

    • 它没有重定向页面应该被重定向但它没有移动
    • 您不需要重定向 - 您可以在请求触发时更改请求路径。此外,如果您使用重定向它应该终止管道并且不调用下一个中间件(即不调用_next.Invoke()
    • 嗨@Tobias,我正在关注您的回答。我将查询字符串附加到重定向 URL,但未在 Startup.cs 文件中的请求 URL 中获取查询字符串参数。
    【解决方案2】:

    只要您在其他触发的中间件之前插入重写中间件,您就可以在中间件代码中重写Context.Request.Path

    路径是可写的,任何后续代码/中间件都将使用新路径来处理请求。

    使用独立的 (app.Use()) 中间件可以做到:

    app.Use(async (context,next) =>
    {
        var url = context.Request.Path.Value;
    
        // Rewrite privacy URL to index
        if (url.Contains("/home/privacy"))
        {
            // rewrite to index
            context.Request.Path = "/home/index";
        }
    
        await next();
    });
    

    Repsonse.Redirect()(触发新的服务器请求)不同,此操​​作不会更改原始请求的 URL。

    此博文中的更多信息:

    Back to Basics: URL Rewriting in ASP.NET Core

    【讨论】:

    • 在 .NET 6 中试过这个。似乎不再起作用。您可以按照指示设置context.Request.Path,它不会抛出错误,但也不会根据需要更改路径。
    猜你喜欢
    • 1970-01-01
    • 2014-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-10
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    相关资源
    最近更新 更多