ASP.NET WebApi HelpPage如何避免显示到同一资源的多个路由

时间:2013-11-13 14:20:38

标签: asp.net-web-api asp.net-routing

我的问题与[此问题]有点类似: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指向同一资源?

2 个答案:

答案 0 :(得分:2)

尝试使用此代码进行多次路由

[RoutePrefix("api")]
public class ProductsController : ApiController
{        
    [Route("customers/{id}")]
    public string Get(int id)
    {
        return "value";
    }

    [Route("product/{id}")]
    public string Getv(int id)
    {
        return "product";
    }
}

在App Start中创建一个类

public class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();
        config.EnsureInitialized();
    }
}

在global.asax

中的应用程序启动中添加以下代码
WebApiConfig.Register(GlobalConfiguration.Configuration);

答案 1 :(得分:1)

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