是否可以自定义ASP.NET Web API的路由机制,以将对API的所有请求路由到一个控制器方法?
Is it possible to customize ASP.NET Web API's routing mechanism to route all requests to the API to one controller method?
如果有请求
www.mysite/api/products/或
www.mysite/api/otherResource/7所有内容都将路由到我的SuperDuperController的Get()方法吗?
All would be routed to my SuperDuperController's Get() method?
推荐答案我遇到了需要这样做的情况. (Web API 2)
I ran into a case where I needed to do this. (Web API 2)
我首先研究了如何创建自定义的IHttpControllerSelector和IHttpActionSelector s.但是,这有点模糊.因此,我最终决定采用这种简单的实现方式.您所要做的就是设置通配符路由.示例:
I first looked into creating custom IHttpControllerSelector and IHttpActionSelectors. However, that was a bit of a murky way around. So I finally settled on this dead simple implementation. All you have to do is setup a wildcard route. Example:
public class SuperDuperController : ApiController { [Route("api/{*url}")] public HttpResponseMessage Get() { // url information Request.RequestUri // route values, including "url" Request.GetRouteData().Values } }任何以"api/"开头的GET请求都将被路由到上述方法.这包括您问题中的上述URL.您必须自己从Request或上下文对象中挖掘信息,因为这会绕过自动路由值和模型解析.
Any GET request that starts with "api/" will get routed to the above method. That includes the above mentioned URLs in your question. You will have to dig out information from the Request or context objects yourself since this circumvents automatic route value and model parsing.
这样做的好处是,您仍然可以使用其他控制器(只要它们的路由不是以"api/"开头).
The good thing about this is you can still use other controllers as well (as long as their routes don't start with "api/").
更多推荐
将所有Web API请求路由到一个控制器方法
发布评论