在Global.asax中将自定义创建的路由添加到路由集合中

时间:2014-07-31 14:37:12

标签: c# asp.net asp.net-mvc asp.net-mvc-4

我是asp.net mvc的新手,所以这可能非常简单。 我正在尝试基于子域进行asp.net mvc路由。我一直关注这个StackOverFlow帖子。我创建了这个类,但我对如何将它添加到Global.asax中的路径集合感到困惑。 我想要完成的是将user1.exmaple.comuser2.example.com路由到带有参数的同一个控制器。 这是自定义创建的路线

public class ExampleRoute : RouteBase
{

    public override RouteData GetRouteData(HttpContextBase httpContext)
    {
        var url = httpContext.Request.Headers["HOST"];
        var index = url.IndexOf(".");

        if (index < 0)
            return null;

        var subDomain = url.Substring(0, index);

        if (subDomain == "user1")
        {
            var routeData = new RouteData(this, new MvcRouteHandler());
            routeData.Values.Add("controller", "User1"); //Goes to the User1Controller class
            routeData.Values.Add("action", "Index"); //Goes to the Index action on the User1Controller

            return routeData;
        }

        if (subDomain == "user2")
        {
            var routeData = new RouteData(this, new MvcRouteHandler());
            routeData.Values.Add("controller", "User2"); //Goes to the User2Controller class
            routeData.Values.Add("action", "Index"); //Goes to the Index action on the User2Controller

            return routeData;
        }

        return null;
    }

    public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
    {
        //Implement your formating Url formating here
        return null;
    }
}

1 个答案:

答案 0 :(得分:1)

您通常会在App_Data \ RouteConfig.cs文件中添加自定义路由

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.Add(new ExampleRoute());
    }
}

确保在Global.asax Application_Start()

中调用它
    protected void Application_Start()
    {
        RouteConfig.RegisterRoutes(RouteTable.Routes);
    }