Redirecting route in ASP.NET WebAPI

耗尽温柔 提交于 2019-12-12 01:11:36

问题


This is ok:

    GlobalConfiguration.Configuration.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{action}",
        defaults: new { id = System.Web.Http.RouteParameter.Optional });

But I want to redirect incoming requests to ApiFolder folder's class


回答1:


You should specify your namespace in your route configuration:

var r = GlobalConfiguration.Configuration.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{action}",
        defaults: new { id = System.Web.Http.RouteParameter.Optional },
);
if( r.DataTokens == null ){
  r.DataTokens = new RouteValueDictionary();
}
r.DataTokens["Namespaces"] = new string[] {"ApiFolder"};



回答2:


Kenneth's suggestion wont work as stated in the comments.

However you can write your own implementation of IHttpControllerSelector and only assign it when you map the api routes. I used the implementation in this article as a base and modified it.

Then its just the small issue of replacing the default selector after mapping the route in WebApiConfig like this (where CustomControllerSelector is my implementation):

    public static void Register(HttpConfiguration configuration)
    {
        var apiRoute = configuration.Routes.MapHttpRoute(
            name: "API Default",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional, controllerNamespace = "api" }
        );

        configuration.Services.Replace(typeof(IHttpControllerSelector), new CustomControllerSelector(configuration));
    }


来源:https://stackoverflow.com/questions/16609561/redirecting-route-in-asp-net-webapi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!