目前,我正在使用下面的代码以编程方式设置我的所有api路由,这很好用。
我想要实现的是以编程方式为每个操作设置2个路由,而不是在每个操作上手动设置两次RouteAttribute("MY_ROUTE")。
这就是我目前设置路由的方式。
public static void Map(ControllerModel model)
{
string templatePrefix = "api/services/app";
...
if (AppStore.Contains(model.ControllerName))
templatePrefix = "api/services/AppStore";
...
foreach (var action in model.Actions)
{
var verb = ProxyScriptingHelper.GetConventionalVerbForMethodName(action.ActionName);
var constraint = new HttpMethodActionConstraint(new List<string> { verb });
foreach (var selector in action.Selectors)
{
selector.ActionConstraints.Add(constraint);
selector.AttributeRouteModel = new AttributeRouteModel(new RouteAttribute($"{templatePrefix.EnsureEndsWith('/')}{action.Controller.ControllerName}/{action.ActionName}"));
}
}
}我尝试过AttributeRouteModel.CombineAttributedRouteModel,但它将路由字符串连接在一起,这不是我所期望的。
使用上面的代码,所有的AppStore控制器动作都变成了
api/services/AppStore/getApps1
api/services/AppStore/getApps2
api/services/AppStore/getApps3我希望得到的结果是
api/services/app/getApps1
api/services/AppStore/getApps1
api/services/app/getApps2
api/services/AppStore/getApps2
api/services/app/getApps3
api/services/AppStore/getApps3发布于 2019-07-17 00:55:52
您可以使用action.Selectors.Add()。目前,您只需使用自定义路由覆盖默认选择器。另外,我认为你的逻辑有一点小缺陷。您正在覆盖templatePrefix,但是您声称您实际上希望注册这两个路由。
您可以尝试类似以下内容的操作:
public static void Map(ControllerModel model)
{
string templatePrefix = "api/services/app";
...
foreach (var action in model.Actions)
{
var verb = ProxyScriptingHelper.GetConventionalVerbForMethodName(action.ActionName);
var constraint = new HttpMethodActionConstraint(new List<string> { verb });
foreach (var selector in action.Selectors)
{
selector.ActionConstraints.Add(constraint);
selector.AttributeRouteModel = new AttributeRouteModel(new RouteAttribute($"{templatePrefix.EnsureEndsWith('/')}{action.Controller.ControllerName}/{action.ActionName}"));
}
if (AppStore.Contains(model.ControllerName))
{
templatePrefix = "api/services/AppStore";
var sm = new SelectorModel
{
AttributeRouteModel = new AttributeRouteModel(new RouteAttribute(
$"{templatePrefix.EnsureEndsWith('/')}{action.Controller.ControllerName}/{action.ActionName}"))
};
sm.ActionConstraints.Add(constraint);
action.Selectors.Add(sm);
}
}
}https://stackoverflow.com/questions/56956156
复制相似问题