c# - MVC 重定向到默认路由

标签 c# asp.net-mvc-3 asp.net-mvc-routing

这是我的默认路线:

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

我们知道,当有人访问 www.domain.com/时,MVC 的路由会根据上面的路由确定默认的 Controller 和执行的 Action ,但是 URL 会保持不变。对于每条使用默认值的路由,是否有内置或优雅的方法来执行从 www.domain.com/到 www.domain.com/uk/{controller}/{action}/的 301 重定向?

最佳答案

我创建了一个自定义路由处理程序,它在路由级别执行重定向。感谢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

关于c# - MVC 重定向到默认路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11518935/

相关文章:

c# - 如何避免服务定位器模式?我是不是该?

c# - 从 Entity Framework 返回自定义对象 <List T> 并分配给对象数据源

asp.net-mvc - ASP.NET MVC3,Html.TextAreaFor 没有编码?

asp.net-mvc-3 - 如何使用 DisplayName 属性和/或 LabelFor 在表单标签中呈现 HTML 链接?

asp.net-mvc - asp mvc : specifying a view name does not change the url

asp.net-mvc - 在 ASP.NET MVC 中避免使用路由规则的 Controller

c# - System.Web.Routing.RouteCollection.GetRouteData 中的异常

c# - 从 C# 中的另一个页面调用函数

c# - 如何重新创建 PowerShell $profile 变量?它在自定义主机中为空

c# - MVC3 下拉列表为