ASP.NET MVC:如何通过ASP.NET Core中的中间件重写URL
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了ASP.NET MVC:如何通过ASP.NET Core中的中间件重写URL,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2418字,纯文字阅读大概需要4分钟。
内容图文
在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
请详细指导我.谢谢
解决方法:
您几乎只需要将代码移至中间件类,并使用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博客文章.
内容总结
以上是互联网集市为您收集整理的ASP.NET MVC:如何通过ASP.NET Core中的中间件重写URL全部内容,希望文章能够帮你解决ASP.NET MVC:如何通过ASP.NET Core中的中间件重写URL所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。