如何格式化我的ASP.NET MVC 5网站的URL

时间:2016-03-17 20:28:21

标签: asp.net asp.net-mvc

我有一个网站,它的网址出现在浏览器上,就像这样:

mysite.com/Produto/PaoDeMel

出于搜索引擎优化的原因,我希望它像:

mysite.com/produto/pao-de-mel

但我的actionname是PaoDeMel,框架不允许我在名称上使用“ - ”。

是否有路由配置或其他任何东西来实现我的目标?

PS:How do I change the url in MVC 5?中建议的解决方案对我不起作用。

由于

1 个答案:

答案 0 :(得分:0)

您需要实现IRouteHandlerIHttpHandler接口(特别关注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);
        }
    }

接下来,添加处理默认路由和自定义路由的路由:

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
                )
        );
}

无论您的网址中有多少个连字符(mysite.com/produto/pao-de-mel,mysite.com/produto/pao-de-mel-abc等),这将被捕获" MyRoute"路由,将由MyRouteHandler处理,将路径转换为可由"默认"处理的网址。通过传输ASP.NET MVC路由的正常流程处理请求来实现此目的。