301 Redirection Layer In Microsoft Asp.net MVC Using Phil Haacked Code Doesn't Work For Me
I need a set up a website that accepts URLs from an older web site version and permenantly redirect them to the new site.
I tried this code from Phil Haack's blog but it seems to redirect everything and severely screw up all route generations.
http://haacked.com/archive/2008/12/15/redirect-routes-and-other-fun-with-routing-and-lambdas.aspx
Has anyone got something like this working?
The important paramenters for defining a redirect for me is targetUrl and destinationUrl
e.g.
routes.RedirectPermanently("about/history","about/heritage");
Would permanently redirect visits to /about/history to /about/heritage.
Haacks APi is perfect, but it just doesn't work. The Route object he uses seems to always be accepted for any routeValues.
Answer
You could always use a catchall at the end of your routes which points to a method that does a redirect, like this source:
public class PermanentRedirectResult : ActionResult
{
public string Url;
public override void ExecuteResult(ControllerContext context)
{
context.HttpContext.Response.StatusCode = 301;
context.HttpContext.Response.RedirectLocation = this.Url;
context.HttpContext.Response.End();
}
}
Here's a (preferred) alternative where you can specify which status code.
public class RedirectWithStatusCodeResult : ActionResult
{
public HttpStatusCode StatusCode { get; set; }
public string Url { get; set; }
public override void ExecuteResult(ControllerContext context)
{
context.HttpContext.Response.StatusCode = (int)this.StatusCode;
context.HttpContext.Response.RedirectLocation = this.Url;
context.HttpContext.Response.End();
}
}
Related Questions
- → How to Fire Resize event after all images resize
- → JavaScript in MVC 5 not being read?
- → URL routing requires /Home/Page?page=1 instead of /Home/Page/1
- → Getting right encoding from HTTPContext
- → How to create a site map using DNN and C#
- → I want integrate shopify into my mvc 4 c# application
- → Bootstrap Nav Collapse via Data Attributes Not Working
- → Shopify api updating variants returned error
- → Get last n quarters in JavaScript
- → ASP.NET C# SEO for each product on detail page on my ECOMMERCE site
- → SEO Meta Tags From Behind Code - C#
- → onchange display GridView record if exist from database using Javascript
- → How to implement search with two terms for a collection?