2012-07-17 8 views
5

をデフォルトにリダイレクトここでは私のデフォルトルートです:私たちが知っているように、誰かがデフォルトのコントローラとアクションを決定しますMVCのルーティングwww.domain.com/訪れたときMVCルート

routes.MapRouteLowercase(
       "Default", 
       "{country}/{controller}/{action}/{id}", 
       new { 
        country = "uk", 
        controller = "Home", 
        action = "Index", 
        id = UrlParameter.Optional 
       }, 
       new[] { "Presentation.Controllers" } 
       ); 

、上記のルートに基づいて実行するには、 URLは同じままです。デフォルトを使用するすべてのルートについて、www.domain.com/からwww.domain.com/uk/{controller}/{action}/への301リダイレクトを実行するための組み込み式またはエレガントな方法がありますか?

+0

デフォルトのコントローラからリダイレクトすることができます。インデックスアクション – codingbiz

答えて

14

ルートレベルでリダイレクトするカスタムルートハンドラを作成しました。 Phil Haackに感謝します。

ここには完全な作業があります。

リダイレクトルートハンドラ

public class RedirectRouteHandler : IRouteHandler 
{ 
    private string _redirectUrl; 

    public RedirectRouteHandler(string redirectUrl) 
    { 
     _redirectUrl = redirectUrl; 
    } 

    public IHttpHandler GetHttpHandler(RequestContext requestContext) 
    { 
     if (_redirectUrl.StartsWith("~/")) 
     { 
      string virtualPath = _redirectUrl.Substring(2); 
      Route route = new Route(virtualPath, null); 
      var vpd = route.GetVirtualPath(requestContext, 
       requestContext.RouteData.Values); 
      if (vpd != null) 
      { 
       _redirectUrl = "~/" + vpd.VirtualPath; 
      } 
     } 

     return new RedirectHandler(_redirectUrl, false); 
    } 
} 

リダイレクトHTTPハンドラ

public class RedirectHandler : IHttpHandler 
{ 
    private readonly string _redirectUrl; 

    public RedirectHandler(string redirectUrl, bool isReusable) 
    { 
     _redirectUrl = redirectUrl; 
     IsReusable = isReusable; 
    } 

    public bool IsReusable { get; private set; } 

    public void ProcessRequest(HttpContext context) 
    { 
     context.Response.Status = "301 Moved Permanently"; 
     context.Response.StatusCode = 301; 
     context.Response.AddHeader("Location", _redirectUrl); 
    } 
} 

ルート拡張

public static class RouteExtensions 
{ 
    public static void Redirect(this RouteCollection routes, string url, string redirectUrl) 
    { 
     routes.Add(new Route(url, new RedirectRouteHandler(redirectUrl))); 
    } 
} 

これらをすべて持っているので、Global.asax.csのルートをマッピングするときにこのようなことができます。

routes.Redirect("", "/uk/Home/Index"); 

routes.Redirect("uk", "/uk/Home/Index"); 

routes.Redirect("uk/Home", "/uk/Home/Index"); 

.. other routes 
+0

非常に徹底した、ありがとう:) – Spikeh

+1

routes.Redirectは他のルート(ex MapRoute)の前に行く必要がありますか?これは古い.aspxページのルーティングのために動作しますか? foo.aspx - >/foo – Seth

6

私のプロジェクトでは、通常、私のルート(URLは表示されません)のデフォルトのアクションとして「実際の」インデックスページ(URLは常に表示される)にリダイレクトされます。

このアクションは、すべてのコントローラクラスの基本クラスで作成できます。

+0

これは最高のソリューションでした! – MEMark

+0

斬新なアイデアは、私が自分自身のことを考えていたらいいのに! – melodiouscode