Csharp/C#教程:MVC重定向到默认路由分享


MVC重定向到默认路由

这是我的默认路线:

routes.MapRouteLowercase( "Default", "{country}/{controller}/{action}/{id}", new { country = "uk", controller = "Home", action = "Index", id = UrlParameter.Optional }, new[] { "Presentation.Controllers" } ); 

众所周知,当有人访问www.domain.com/时,MVC的路由将根据上述路由确定默认控制器和要执行的操作,但URL将保持不变。 对于使用默认值的每条路线,是否有内置或优雅的方式从www.domain.com/执行301重定向到www.domain.com/uk/{controller}/{action}/?

我创建了一个自定义路由处理程序,在路由级别执行重定向。 感谢Phil Haack 。

这是完整的工作。

重定向路由处理程序

 public class RedirectRouteHandler : IRouteHandler { private string _redirectUrl; public RedirectRouteHandler(string redirectUrl) { _redirectUrl = redirectUrl; } public IHttpHandler GetHttpHandler(RequestContext requestContext) { if (_redirectUrl.StartsWith("~/")) { string virtualPath = _redirectUrl.Substring(2); Route route = new Route(virtualPath, null); var vpd = route.GetVirtualPath(requestContext, requestContext.RouteData.Values); if (vpd != null) { _redirectUrl = "~/" + vpd.VirtualPath; } } return new RedirectHandler(_redirectUrl, false); } } 

重定向http处理程序

 public class RedirectHandler : IHttpHandler { private readonly string _redirectUrl; public RedirectHandler(string redirectUrl, bool isReusable) { _redirectUrl = redirectUrl; IsReusable = isReusable; } public bool IsReusable { get; private set; } public void ProcessRequest(HttpContext context) { context.Response.Status = "301 Moved Permanently"; context.Response.StatusCode = 301; context.Response.AddHeader("Location", _redirectUrl); } } 

路线扩展

 public static class RouteExtensions { public static void Redirect(this RouteCollection routes, string url, string redirectUrl) { routes.Add(new Route(url, new RedirectRouteHandler(redirectUrl))); } } 

拥有所有这些,我可以在Global.asax.cs中映射路由时执行类似的操作。

 routes.Redirect("", "/uk/Home/Index"); routes.Redirect("uk", "/uk/Home/Index"); routes.Redirect("uk/Home", "/uk/Home/Index"); .. other routes 

在我的项目中,我通常将“IndexRedirect”作为我的路径中的默认操作(其URL将永远不可见),除了重定向到“真实”索引页(其URL始终可见)之外什么都不做。

您可以在所有控制器类的基类中创建此操作。

上述就是C#学习教程:MVC重定向到默认路由分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/936530.html

(0)
上一篇 2021年11月7日
下一篇 2021年11月7日

精彩推荐