1

我的问题在某种程度上类似于 [this question]: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 会指向相同的资源?

4

2 回答 2

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 的 application start 中添加以下代码

WebApiConfig.Register(GlobalConfiguration.Configuration);
于 2013-11-14T09:30:07.327 回答
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;
    }
}
于 2013-11-13T16:21:06.057 回答