5

これが私のデフォルトルートです:

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

ご存知のように、誰かが www.domain.com/ にアクセスすると、MVC のルーティングによって、上記のルートに基づいて実行するデフォルトのコントローラーとアクションが決定されますが、URL は同じままです。デフォルトを使用するすべてのルートに対して、www.domain.com/ から www.domain.com/uk/{controller}/{action}/ への 301 リダイレクトを実行する組み込みまたはエレガントな方法はありますか?

4

2 に答える 2

15

ルート レベルでリダイレクトを行うカスタム ルート ハンドラを作成しました。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
于 2012-07-17T10:39:18.607 に答える
7

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

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

于 2012-07-17T09:28:14.603 に答える