MVC Routing - changing routes

廉价感情. 提交于 2020-01-16 01:54:07

问题


Using MVC4, I have the following routing for a blog post detail action which is SEO friendly URLS:

public ActionResult Details(int id, string postName)
{
    BlogPost blogPost = _blogService.GetBlogPostById(id);
    string expectedName = blogPost.Title.ToSeoUrl();
    string actualName = (postName ?? "").ToLower();

    if (expectedName != actualName)
        return RedirectToAction("Details", "Blog", new { id = blogPost.BlogPostId, postName = expectedName });

    var vm = BuildBlogPostDetailViewModel(id);
    return View(vm);
}

The SEO route is constructed using the following helper method:

public static class Helper
{
    public static string ToSeoUrl(this string url)
    {
        // ensure the the is url lowercase
        string encodedUrl = (url ?? "").ToLower();

        // replace & with and
        encodedUrl = Regex.Replace(encodedUrl, @"\&+", "and");

        // remove characters
        encodedUrl = encodedUrl.Replace("'", "");

        // remove invalid characters
        encodedUrl = Regex.Replace(encodedUrl, @"[^a-z0-9]", "-");

        // remove duplicates
        encodedUrl = Regex.Replace(encodedUrl, @"-+", "-");

        // trim leading & trailing characters
        encodedUrl = encodedUrl.Trim('-');

        return encodedUrl;
    }
}

This produces a route like so:

/Blog/Details/1?postName=user-group-2013

What I am trying to achieve is the following route:

/Blog/Details/user-group-2013

Any suggestions on how to achieve and optimize this?

Many Thanks


回答1:


Try this

return RedirectToAction("Details", "Blog", new { blogPost.BlogPostId,expectedName });



回答2:


You may try to change you routing in RouteConfig class.

Seems you are having there just default route:

routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );

And one more route BEFORE default route:

// This route will return /Blog/Details/1/user-group-2013
routes.MapRoute(
     name: "MyRoute",
     url: "{controller}/{action}/{id}/{postName}",
     defaults: new { controller = "Blog", action = "Details", id = UrlParameter.Optional, postName = UrlParameter.Optional}
            );

// Or this route. It should return /Blog/Details/user-group-2013
routes.MapRoute(
     name: "MyRoute2",
     url: "{controller}/{action}/{postName}",
     defaults: new { controller = "Blog", action = "Details", id = UrlParameter.Optional, postName = UrlParameter.Optional}
            );


来源:https://stackoverflow.com/questions/18784979/mvc-routing-changing-routes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!