views:

316

answers:

2

I'd like to add a trailing slash to any url's that match a valid route but do not currently end in a slash, i.e. www.example.com/url

After a url is matched to a valid route I would like to 301 redirect to the same url but add the trailing slash i.e. www.example.com/url/

I've spent some time looking into it but I can't seem to figure it out.

I believe routes are matched in the PostResolveRequestCache event, but I don't know how to access the routedata during or after that event to see if a valid route was matched. If I can confirm that a valid route was matched then I can check the url to make sure it ends in a slash.

I hope that's clear enough, let me know if you need more info.

A: 

I assume you are trying to eliminate duplicate content for SEO purposes.

Scott Hanselman says you can do this with the IIS7 Rewrite module (are you running IIS7?) His post at http://www.hanselman.com/blog/ASPNETMVCAndTheNewIIS7RewriteModule.aspx describes the process.

Robert Harvey
Yes, I'm trying to insure I don't have multiple paths to the same content.Right now I'm running IIS6, but I have a rewrite module installed so I could use this approach I suppose. This would rewrite all incoming requests though, I'd like to only rewrite valid routes and leave invalid url's as they were.I actually ended up using an action filter on my base controller to rewrite any url's that don't end in a slash. That's working pretty well so far.See this url for what I used...http://www.devproconnections.com/tabId/180/itemId/4576/Putting-the-IIS-SEO-Toolkit-to-work-with-ASPNET-M.aspx
Paul
A: 

This sounds like a perfect fit for action filter:

public class EnforceTrailingSlashAttribute : ActionFilterAttribute
{
   public override void OnActionExecuting(ActionExecutingContext filterContext)
   {
      if (!filterContext.HttpContext.Request.Path.EndsWith("/"))
      {
         filterContext.Result = new RedirectResult(
            filterContext.HttpContext.Request.Path + "/");            
      }
   }
}
Pavel Chuchuva