[英]How to format the URL of my ASP.NET MVC 5 website
I have a website and it's url appears on the browser llike this: 我有一个网站,它的网址出现在浏览器中,如下所示:
mysite.com/Produto/PaoDeMel mysite.com/Produto/PaoDeMel
and for SEO reasons I'd like it to be like: 并且出于SEO的原因,我希望它像:
mysite.com/produto/pao-de-mel mysite.com/produto/pao-de-mel
but my actionname is PaoDeMel, and the framework doesn't let me use "-" on the name. 但我的动作名称是PaoDeMel,并且该框架不允许我在名称上使用“-”。
Is there a routing config or anything else to achieve my goal? 是否有路由配置或其他任何方式可以实现我的目标?
PS.: the solution suggested in How do I change the url in MVC 5? PS .: 如何在MVC 5中更改URL中建议的解决方案? didn't work for me.
没有为我工作。
Thanks 谢谢
You need to implement IRouteHandler
and IHttpHandler
interfaces (special attention on ProcessRequest method of IHttpHandler implementation): 您需要实现
IRouteHandler
和IHttpHandler
接口(特别注意IHttpHandler实现的ProcessRequest方法):
public class MyRouteHandler : IRouteHandler
{
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
return new MyHttpHandler();
}
}
public class MyHttpHandler : IHttpHandler
{
public bool IsReusable
{
get
{
return true;
}
}
public void ProcessRequest(HttpContext context)
{
// Take routes values to build a url string that can be handled by "Default" route
string url = "/" + context.Request.RequestContext.RouteData.Values["controller"].ToString().ToLower();
url += "/" + (context.Request.RequestContext.RouteData.Values["part1"] as string).Replace("-", "").ToLower() + (context.Request.RequestContext.RouteData.Values["part2"] as string).Replace("-", "").ToLower();
url += "/" + context.Request.RequestContext.RouteData.Values["id"];
context.Server.TransferRequest(url, true);
}
}
Next, add routes that handle default and custom routing: 接下来,添加处理默认和自定义路由的路由:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
constraints: new { action = @"[^\-]*" }
);
routes.Add("MyRoute",
new Route("{controller}/{part1}-{part2}/{id}",
new RouteValueDictionary { { "controller", "Home" }, { "action", "Index" }, { "id", "" } },
new MyRouteHandler() // Custom route handler
)
);
}
No matter how many hyphens have your url in action segment (mysite.com/produto/pao-de-mel, mysite.com/produto/pao-de-mel-abc, etc.), this will be captured by the "MyRoute" route, and will be processed by MyRouteHandler
that will transform the path into a url that can be handled by the "Default" route, achieving this, by transfering the request to be processed by normal flow of ASP.NET MVC Routing. 无论您的网址在操作段中有多少个连字符(mysite.com/produto/pao-de-mel、mysite.com/produto/pao-de-mel-abc等),都会由“ MyRoute”捕获”路由,并将由
MyRouteHandler
处理,该路由会将路径转换为可以由“默认”路由处理的url,从而通过转移要由ASP.NET MVC路由的常规流程处理的请求来实现此目的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.