Skip to content

Instantly share code, notes, and snippets.

@hayashih
Created November 29, 2010 11:29
Show Gist options
  • Save hayashih/719855 to your computer and use it in GitHub Desktop.
Save hayashih/719855 to your computer and use it in GitHub Desktop.
ASP.NET MVC Grobal.asax.cs sample for redirect no trailing slash url.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
namespace MyMvcWebSite
{
// メモ: IIS6 または IIS7 のクラシック モードの詳細については、
// http://go.microsoft.com/?LinkId=9394801 を参照してください
public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.Add("Root",
new TrailingSlashRoute(
"",
new RouteValueDictionary( new { controller = "Home", action = "Index" } ),
new TrailingSlashRouteHandler(),
"Index"
)
);
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);
}
}
public class TrailingSlashRoute : Route
{
public TrailingSlashRoute(string url, RouteValueDictionary defaults, IRouteHandler routeHandler, string redirectActionName)
: base(url, defaults, routeHandler)
{
this.RedirectActionName = redirectActionName;
}
public string RedirectActionName { get; set; }
}
public class TrailingSlashRouteHandler : IRouteHandler
{
#region IRouteHandler メンバー
IHttpHandler IRouteHandler.GetHttpHandler(RequestContext requestContext)
{
return new TrailingSlashHandler(requestContext);
}
#endregion
}
public class TrailingSlashHandler : MvcHandler
{
public TrailingSlashHandler(RequestContext requestContext) : base(requestContext) { }
protected override IAsyncResult BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, object state)
{
String absolutePath = httpContext.Request.Url.AbsolutePath;
if (absolutePath.EndsWith("/") == false)
{
httpContext.Response.StatusCode = 301;
httpContext.Response.AddHeader("Location", absolutePath + "/");
}
return base.BeginProcessRequest(httpContext, callback, state);
}
protected override void EndProcessRequest(IAsyncResult asyncResult)
{
base.EndProcessRequest(asyncResult);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment