以下是如何实现此目的的示例。在这里,我正在创建一个自定义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;
}
}