gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 15:20:04 25 4
gpt4 key购买 nike

在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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com