如何在asp.net mvc中的url中添加页面标题?(网址生成)

Ant*_*nte 16 url asp.net-mvc seo routing

如何动态创建网址/链接,例如:www.restaurant.com/restaurant/restaurant-name-without-some-characters-like-space-coma-etc/132

我可以用什么关键词来搜索关于这个主题的一些文章?(如何在asp.net mvc中生成和处理这种URL)

有一些问题:如何生成链接?(在db中存储slu ???)如果slug不是规范的话,是否重定向?

编辑:显然他们被称为slugs

Meh*_*hin 6

你必须使用如下的东西.

Routes.MapRoute(
    "Post",
    "posts/{id}/{*title}",
    new { controller = "Posts", action = "view" }
);
Run Code Online (Sandbox Code Playgroud)

还有一个简单的扩展方法:

public static class UrlExtensions
{

    public static string ResolveSubjectForUrl(this HtmlHelper source, string subject)
    {
        return Regex.Replace(Regex.Replace(subject, "[^\\w]", "-"), "[-]{2,}", "-");
    }

}
Run Code Online (Sandbox Code Playgroud)


Oma*_*mar 2

执行此操作的一种方法是在字符串上执行以下操作

 string cleanString = originalString.ToLower().Replace(" ", "-"); // ToLower() on the string thenreplaces spaces with hyphens
 cleanString = Regex.Replace(cleanString, @"[^a-zA-Z0-9\/_|+ -]", ""); // removes all non-alphanumerics/underscore/hyphens
Run Code Online (Sandbox Code Playgroud)

现在您可以将cleanString(标题、名称等)传递到 ActoinLink/Url.Action 参数中,它会很好用。

该模式取自http://snipplr.com/view/18414/string-to-clean-url-generator/

我并不是 100% 支持正则表达式模式,如果某个正则表达式英雄可以插话并提供一个更好的模式,那就太好了。通过测试正则表达式,它不匹配空格,但这应该不是问题,因为第一行用连字符替换所有空格。

更新:

要使用此代码,您需要设置路由以接受额外参数。

我们将使用博客文章标题作为示例。

        routes.MapRoute(
            "",                                              // Route name
            "View/{ID}/{Title}",                           // URL with parameters
            new { controller = "Articles", action = "View"}  // Parameter defaults
        );
Run Code Online (Sandbox Code Playgroud)

在 ASP.NET MVC 视图中,您可以执行以下操作:

  <%= Html.ActionLink("View Article", "View", "Articles", new { ID = article.ID, Title = Html.SanitizeTitle(article.Title) }, null) %>
Run Code Online (Sandbox Code Playgroud)

在前面的示例中,我将其用作HTML 帮助SanitizeTitle程序。

public static string SanitizeTitle(this HtmlHelper html, string originalString)
{
     string cleanString = originalString.ToLower().Replace(" ", "-"); // ToLower() on the string then replaces spaces with hyphens
     cleanString = Regex.Replace(cleanString, @"[^a-zA-Z0-9\/_|+ -]", ""); // removes all non-alphanumerics/underscore/hyphens
     return cleanString;
}
Run Code Online (Sandbox Code Playgroud)