我的问题在某种程度上类似于这个问题WebApi help and multipe routes
我有一些自定义路由定义,如下所示
config.Routes.MapHttpRoute(
name: "NewsTopHeaders",
routeTemplate: "api/news/headers/top",
defaults: new { controller = "News", action = "GetTopHeaders" }
);当然还有默认路由(以涵盖不需要自定义路由的所有内容)
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}",
defaults: new {}
);有没有可能从默认路由中排除一些操作-这样就不会有重复的url指向相同的资源?
发布于 2013-11-14 00:21:06
下面是一个如何实现这一目标的示例。在这里,我创建了一个自定义的ApiExplorer( HelpPage使用它取决于它),它检查给定的操作和路由,并决定是否显示该操作。请注意,我使用数据令牌来存储路由名称,以便稍后轻松检查。我这样做是因为在给定路由的Web API中,您无法从中获取名称,因此我们在这里将一些自定义信息插入到datatokens字典中。
config.Services.Replace(typeof(IApiExplorer), new CustomApiExplorer(config));
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional },
dataTokens: new { routeName = "DefaultApi" },
constraints: null,
handler:null
);public class CustomApiExplorer : ApiExplorer
{
public CustomApiExplorer(HttpConfiguration config) : base(config) { }
public override bool ShouldExploreAction(string actionVariableValue, HttpActionDescriptor actionDescriptor, IHttpRoute route)
{
//get current route name
string routeNameKey = "routeName";
if(route.DataTokens.ContainsKey(routeNameKey))
{
string routeName = (string)route.DataTokens[routeNameKey];
ReflectedHttpActionDescriptor descriptor = (ReflectedHttpActionDescriptor)actionDescriptor;
if(routeName == "DefaultApi"
&& descriptor.ControllerDescriptor.ControllerType == typeof(ValuesController)
&& descriptor.ActionName == "Something")
{
return false; //do not show this action for this particular route
}
}
// for other actions let the default behavior take place
return base.ShouldExploreAction(actionVariableValue, actionDescriptor, route);
}
}
/// <summary>
/// Out of the box Web API doesn't provide any 'MapHttpRoute' extension which takes in the 'data tokens', so here
/// we are creating a new extension.
/// </summary>
public static class MyExtensions
{
public static IHttpRoute MapHttpRoute(this HttpRouteCollection routes, string name, string routeTemplate,
object defaults, object constraints, object dataTokens,
HttpMessageHandler handler)
{
if (routes == null)
{
throw new ArgumentNullException("routes");
}
HttpRouteValueDictionary defaultsDictionary = new HttpRouteValueDictionary(defaults);
HttpRouteValueDictionary constraintsDictionary = new HttpRouteValueDictionary(constraints);
HttpRouteValueDictionary dataTokensDictionary = new HttpRouteValueDictionary(dataTokens);
IHttpRoute route = routes.CreateRoute(routeTemplate, defaultsDictionary, constraintsDictionary, dataTokensDictionary, handler: handler);
routes.Add(name, route);
return route;
}
}https://stackoverflow.com/questions/19956137
复制相似问题