无法将“RouteCollectionRoute”类型的对象强制转换为“Routing.Route”

时间:2015-07-04 16:52:38

标签: c# asp.net-mvc asp.net-mvc-5 asp.net-mvc-routing

我正在尝试将{culture}标记添加到所有生成的网址。

  

无法投射类型的对象   输入'System.Web.Mvc.Routing.RouteCollectionRoute'   'System.Web.Routing.Route'。

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.MapMvcAttributeRoutes();

        using (routes.GetReadLock())
        {
            foreach (Route r in routes)
            {
                if (!(r.RouteHandler is SingleCultureMvcRouteHandler))
                {
                    r.RouteHandler = new MultiCultureMvcRouteHandler();
                    r.Url = "{culture}/" + r.Url;
                    //Adding default culture 
                    if (r.Defaults == null)
                    {
                        r.Defaults = new RouteValueDictionary();
                    }
                    r.Defaults.Add("culture", Culture.en.ToString());

                    //Adding constraint for culture param
                    if (r.Constraints == null)
                    {
                        r.Constraints = new RouteValueDictionary();
                    }
                    r.Constraints.Add("culture", new CultureConstraint(Culture.en.ToString(),
         Culture.nl.ToString()));
                }
            }
        }
    }

我有一个名为MapCultureRoute的方法,它创建了两个路径,一个以{culture}为前缀,但这不适用于属性路由。

MapCultureRoute:

public static void MapCultureRoute(string name, string url, object defaults, object constraints = null)
{
    var c = CultureHelper.GetDefaultCulture();
    var d = new ExpandoObject() as IDictionary<string, object>;


    var t = defaults.GetType();

    var pi = t.GetProperties();

    foreach (var p in pi)
    {
        d.Add(p.Name, p.GetValue(defaults, null));
    }

    //map route with specified culture
    RouteTable.Routes.MapRoute(
        name: name,
        url: "{culture}/" + url,
        defaults: defaults,
        constraints: constraints
        );

    //map route with default culture
    RouteTable.Routes.MapRoute(
        name: name + "-DefaultCulture",
        url: url,
        defaults: d,
        constraints: constraints
        );
}

0 个答案:

没有答案