首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >MVC路由更改路由

MVC路由更改路由
EN

Stack Overflow用户
提问于 2013-09-13 11:15:16
回答 2查看 213关注 0票数 1

使用MVC4,我对博客文章的详细操作有如下的路由,这是SEO友好的URLS:

代码语言:javascript
复制
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);
}

SEO路由使用以下辅助方法构建:

代码语言:javascript
复制
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;
    }
}

这产生了一条类似这样的路线:

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

我所要达到的目标是:

/Blog/Details/用户组-2013年

对于如何实现和优化这一点,有什么建议吗?

非常感谢

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-09-13 11:17:39

尝尝这个

代码语言:javascript
复制
return RedirectToAction("Details", "Blog", new { blogPost.BlogPostId,expectedName });
票数 1
EN

Stack Overflow用户

发布于 2013-09-13 14:15:17

您可以尝试更改RouteConfig类中的路由。

似乎你有一个默认的路线:

代码语言:javascript
复制
routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );

在默认路由之前,还有一条路径:

代码语言:javascript
复制
// 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}
            );
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18784979

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档