我不知道为什么在创建继承自CustomRoute
的{{1}}时,字段Route
会被忽略。
我收到错误: 发现多个类型与名为“Home”的控制器匹配。如果为此请求提供服务的路由('{action} / {id}')未指定名称空间来搜索与请求匹配的控制器,则会发生这种情况。如果是这种情况,请通过调用带有'namespaces'参数的'MapRoute'方法的重载来注册此路由。 以下是样本:
的Application_Start()
DataTokens["Namespaces"]
DomainRoute.cs
public static void RegisterRoutes(RouteCollection routes)
{
//Create dataTokens object
var dataTokens = new RouteValueDictionary();
var ns = new[] {"MvcDomainRouting.Controllers.Delivery" };
dataTokens["Namespaces"] = ns;
//Note is a custom route
routes.Add("DomainRoute", new DomainRoute(
domain:"delivery.md", // Domain with parameters
url:"{action}/{id}", // URL with parameters
defaults: new { controller = "Home", action = "Index", id = "" },// Parameter defaults
constraints:null,
dataTokens: dataTokens,
routeHandler:new MvcRouteHandler()
));
}
来自public class DomainRoute : Route
{
public string Domain { get; set; }
public DomainRoute(string domain, string url, object defaults, object constraints,object dataTokens, IRouteHandler routeHandler)
: base(url, new RouteValueDictionary(defaults), new RouteValueDictionary(constraints), new RouteValueDictionary(dataTokens), routeHandler)
{
Domain = domain;
}
public override RouteData GetRouteData(HttpContextBase httpContext)
{
//Details ommited
// Route data
RouteData data = new RouteData(this, RouteHandler);
// 1.Add defaults
// 2.Map URL key/values
// Copy the DataTokens from the Route to the RouteData
if (DataTokens != null)
{
foreach (var prop in DataTokens)
{
data.DataTokens[prop.Key] = prop.Value;
}
}
return data;
// At this point `data` holds the DataTokens["Namespaces"] see picture
}
}
的堆栈跟踪:
HomeController.cs
return data;
答案 0 :(得分:3)
问题在于我正在创建RouteValueDictionary
RouteValueDictionary
。
这是固定版本:
像这样:
public DomainRoute( ...,object dataTokens,...)
: base(...,dataTokens as RouteValueDictionary ,...)
// instead of
// : base(...,new RouteValueDictionary(dataTokens),..)
{
Domain = domain;
}
或者像这样
//....
constraints:null,
namespaces: new []{"MvcDomainRouting.Controllers.Delivery" },
routeHandler:new MvcRouteHandler()
));
public DomainRoute( ...,string[] namespaces,...)
: base(...,new RouteValueDictionary(){{"Namespaces",namespaces}} ,...)
{
}