c# - ASP.Net MVC :How to rewrite url by middleware in ASP. 网络核心

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

在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://learn.microsoft.com/en-us/aspnet/core/migration/http-modules

最佳答案

您几乎只需要将代码移至中间件类,并使用 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有关中间件的更多信息的博客文章。

关于c# - ASP.Net MVC :How to rewrite url by middleware in ASP. 网络核心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41101945/

相关文章:

c# - 从 .Net 核心中的十六进制获取颜色名称(不使用 System.Drawing.Color)C#

dependency-injection - ASP.NET 5 依赖注入(inject) - [FromServices] 属性是否仅在 Controller 中有效?

performance - Sitecore HttpModules 正在第二次初始化

c# - ASP.NET HttpModules 和 Server.Transfer/Server.TransferRequest/RewritePath 问题

c# - 以编程方式确定路径是否受限

c# - 使用 GetRDOObjectFromOutlookObject 时,兑换邮件对象未正确链接到原始邮件项目

c# - 仅处理来自某些程序集的未处理异常

c# - HttpContext 和 SignalR HubCallerContext 之间的统一静态类

c# - 具有不同 Controller 但相同操作名称的路由无法生成所需的 url

java - C#'s CultureInfo.InvariantCulture and Java' s Locale.ROOT 是否相等?