您需要實現IRouteHandler
和IHttpHandler
接口(在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」路由捕獲,並將被處理,該路徑將把路徑轉換成可以是通過「默認」路由處理,實現這一點,通過傳輸要被ASP.NET MVC路由的正常流程處理的請求。
這裏有一些指導http://stackoverflow.com/questions/2787053/iis7-and-enforce-lowercase-urls – Jasen
'ActionName'怎麼不起作用?另一種方法是創建一個能夠捕獲URL的路由,並且有一個操作方法,將URL段轉換爲某個與您的數據庫中的產品相對應的Id。 –
您必須爲「在MVC中翻譯網址」創建您自己的「Routes」查找 –