Asp.Net MVC 301 Redirects

2019-01-23 18:06发布

问题:

We used to use ISAPI Re-Write (Infact its still on our server) although it doesnt work with ASP.Net MVC (Somthing to do with 'euxd' get param).

We need a relaiable way to implement simple 301 redirects, when we change the site structure, upload a new site etc. Any suggestions?

Ok, it I wanted to redirect /SomeFolder/SomePage.HTML?Param1=X to /NewPage/X

How can we do that?

回答1:

If you are using IIS7, I would recommend using the official IIS7 URL Rewrite module.

  • Using the URL Rewrite Module
  • Using URL Rewrite Module 2.0


回答2:

In MVC 3 there are three new redirect methods that can be used in controllers to redirect permanently (produce a 301); as opposed to the 302s (temporary redirect) produced by the MVC 2 redirects.

  • RedirectPermanent
  • RedirectToActionPermanent
  • RedirectToRoutePermanent
public ActionResult OldAction()
{
  return RedirectPermanent(urlname);
}

There is a great tutorial in the Controllers section of these walkthroughs on PluralSight.



回答3:

To perform a redirect from a non-MVC page to an MVC controller action your best bet is to use a library like UrlRewriting.net or similar which uses an HttpModule to process each request and dispatch it to a specific location.

Example: Redirect requests for '/faq.asp' to '/faq':

<add name="faq.asp" virtualUrl="^~/faq.asp([\?#].*)?$"
            destinationUrl="~/faq"
            redirect="Application"
            redirectMode="Permanent"
            ignoreCase="true" />

When you add the HttpModule that powers UrlRewriting.Net to your Web.config, make sure you define it before the UrlRoutingModule which is defined by ASP.NET automatically. Otherwise, ASP.NET will attempt to handle your request by mapping it to a a file or controller and you may experience some unexpected problems as a result.

<modules runAllManagedModulesForAllRequests="true">
    <add name="UrlRewriteModule" type="UrlRewritingNet.Web.UrlRewriteModule, UrlRewritingNet.UrlRewriter"/>
    <add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</modules>


回答4:

I just blogged about a simple solution that uses ASP.NET MVC and an XML file to store the 301 redirect mappings.

However, as per Nathan Taylor's answer, if you need to do Regex based mapping, I would suggest using UrlRewriting.Net.



回答5:

Implement custom ActionResult. Example: http://www.stum.de/2008/10/22/permanentredirectresult/