开发者

How to add namespace to custom route extension

Im using routes.add instead of routes.maproute (which has a namespace arg) because I extended the Route Class. I need to add namespace on the routes because on开发者_Python百科e of my Areas has the same controller name within the site. My problem is I dont know where to put the namespace..


public class CultureRoute : Route
{
     public CultureRoute(string url, object defaults, object constraints, RouteValueDictionary dataTokens)
            : base(url, new RouteValueDictionary(constraints), dataTokens, new MvcRouteHandler())
        {
        }
}

Global.asax


routes.Add("Default", new CultureRoute(
    "{controller}/{action}/{id}",
    new {controller = "Home", action = "Index", id = UrlParameter.Optional}));



var dataTokens = new RouteValueDictionary();
var ns = new string[] {"MyProject.Controllers"};
dataTokens["Namespaces"] = ns;

routes.Add("Default", new CultureRoute(
    "{controller}/{action}/{id}",
    new { controller = "Home", action = "Index", id = UrlParameter.Optional },
    null /*constraints*/,
    dataTokens
));


EDIT: (Previously created a custom route but that wasn't necessary). This should do the trick. At least it does in MVC 4 and most probably MVC 3

Route defRoute = new CultureRoute ("{controller}/{action}/{id}",
            new RouteValueDictionary(new { controller = "Home", action = "Index", id = UrlParameter.Optional }),
            new SomeRouteHandler());
if( defRoute.DataTokens == null )
      defRoute.DataTokens = new RouteValueDictionary();
defRoute.DataTokens.Add("Namespaces", new string[] { "MVCApp.WebUI.Controllers" });
        routes.Add(defRoute);


For those who were hunting for a solution for this:

You first need a constructor that accepts the DataTokens argument, and pass that through to the Route constructor.

For example, I was using a DomainRoute class I picked up online, which did not have the additional arguments required to pass through to Domain. So I simply implemented a constructor similar to the base Route constructor:

public DomainRoute(string domain, string url, object defaults, object constraints, object dataTokens)
              : base(url, new RouteValueDictionary(defaults), new RouteValueDictionary(constraints),new RouteValueDictionary(dataTokens),new MvcRouteHandler())
{
              Domain = domain;
}

Next, if you have overriden your GetRouteData method, you must return the DataTokens in your RouteData return value. In order to figure this out, I had to look in the Route.cs source code (THANK YOU JAVA2S).

RouteData data = new RouteData(...);
RouteValueDictionary dataTokens = DataTokens;
if (this.DataTokens != null) {
   RouteValueDictionary rdDataTokens = rd.DataTokens;
   foreach (var token in dataTokens)
      rdDataTokens.Add (token.Key, token.Value);
   }
}
return data;

Now simply put in your namespaces in dataTokens["Namespaces"] as per Fleents post.

Regards, Daryl

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜