/dinners/details/2
ASP.NET MVC で、小文字、そして可能であればアンダースコアを含むルートを使用するにはどうすればよいでしょうか。 callDinnersController.Details(2)
と、可能であれば/dinners/more_details/2
call を使用できるようにするにはどうすればよいですかDinnersController.MoreDetails(2)
。
これらすべてを、 のようなパターンを使用しながら実行します{controller}/{action}/{id}
。
ベストアンサー1
System.Web.Routing 4.5 では、RouteCollection の LowercaseUrls プロパティを設定することでこれを簡単に実装できます。
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.LowercaseUrls = true;
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
また、SEO 上の理由でこれを実行していると仮定すると、受信 URL を小文字にリダイレクトする必要があります (この記事のリンクの多くで述べられているように)。
protected void Application_BeginRequest(object sender, EventArgs e)
{
//You don't want to redirect on posts, or images/css/js
bool isGet = HttpContext.Current.Request.RequestType.ToLowerInvariant().Contains("get");
if (isGet && !HttpContext.Current.Request.Url.AbsolutePath.Contains("."))
{
//You don't want to modify URL encoded chars (ex.: %C3%8D that's code to Í accented I) to lowercase, than you need do decode the URL
string urlLowercase = Request.Url.Scheme + "://" + HttpUtility.UrlDecode(HttpContext.Current.Request.Url.Authority + HttpContext.Current.Request.Url.AbsolutePath);
//You want to consider accented chars in uppercase check
if (Regex.IsMatch(urlLowercase, @"[A-Z]") || Regex.IsMatch(urlLowercase, @"[ÀÈÌÒÙÁÉÍÓÚÂÊÎÔÛÃÕÄËÏÖÜÝÑ]"))
{
//You don't want to change casing on query strings
urlLowercase = urlLowercase.ToLower() + HttpContext.Current.Request.Url.Query;
Response.Clear();
Response.Status = "301 Moved Permanently";
Response.AddHeader("Location", urlLowercase);
Response.End();
}
}
}