我要求生成我的网址
/2013/10/custome-mvc-url-rout-to-display-mixture-of-id-and-urlslug
我已经看到许多问题要实现它&我的问题可能有重复..喜欢: -
asp-net-mvc-framework-part-2-url-routing
custome-mvc-url-rout-to-display-mixture-of-id-and-urlslug
等...
我已经实现了如下: -
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
"Post",
"{year}/{month}/{title}",
new { controller = "Blog", action = "Post" }
);
我的Hyperlink会生成这个: -
@Html.ActionLink("continue...", "post", "blog",
new {
year = Model.PostedOn.Year,
month = Model.PostedOn.Month,
day = Model.PostedOn.Day,
title = Model.UrlSlug
}, new { title = "continue..." })
我的MVC控制器是: -
public ViewResult Post(int year, int month, string title)
{}
但是这里的问题是,我的网址为:
http://localhost:2083/blog/post?Year=2013&Month=10&Day=9&title=best_practices_in_programming
而不是: -
http://localhost:2083/blog/post/2013/10/best_practices_in_programming
我做错了什么?请有人指出它。
Thnks!
答案 0 :(得分:0)
我试过这个,只要你把这条路线放在RouteConfig.cs中的默认路线之前就行了,这样:
routes.MapRoute(
null,
"{year}/{month}/{title}",
new { controller = "Blog", action = "Post" },
new { year = @"\d+", month = @"\d+", title = @"[\w\-]*" });
您还应该更改标题以使用连字符而不是下划线IMO。这是一个很好的帮手。
#region ToSlug(), AsMovedPermanently
public static class PermanentRedirectionExtensions
{
public static PermanentRedirectToRouteResult AsMovedPermanently
(this RedirectToRouteResult redirection)
{
return new PermanentRedirectToRouteResult(redirection);
}
}
public class PermanentRedirectToRouteResult : ActionResult
{
public RedirectToRouteResult Redirection { get; private set; }
public PermanentRedirectToRouteResult(RedirectToRouteResult redirection)
{
this.Redirection = redirection;
}
public override void ExecuteResult(ControllerContext context)
{
// After setting up a normal redirection, switch it to a 301
Redirection.ExecuteResult(context);
context.HttpContext.Response.StatusCode = 301;
context.HttpContext.Response.Status = "301 Moved Permanently";
}
}
public static class StringExtensions
{
private static readonly Encoding Encoding = Encoding.GetEncoding("Cyrillic");
public static string RemoveAccent(this string value)
{
byte[] bytes = Encoding.GetBytes(value);
return Encoding.ASCII.GetString(bytes);
}
public static string ToSlug(this string value)
{
if (string.IsNullOrWhiteSpace(value))
{
return string.Empty;
}
var str = value.RemoveAccent().ToLowerInvariant();
str = Regex.Replace(str, @"[^a-z0-9\s-]", "");
str = Regex.Replace(str, @"\s+", " ").Trim();
str = str.Substring(0, str.Length <= 200 ? str.Length : 200).Trim();
str = Regex.Replace(str, @"\s", "-");
str = Regex.Replace(str, @"-+", "-");
return str;
}
}
#endregion
然后你还需要一个帮助器,用url参数标题中的空格替换每个连字符,你可能会传递给控制器操作Post以查询数据库中的Post。