将所有Web API请求路由到一个控制器方法 [英] Route all Web API requests to one controller method

查看:175
本文介绍了将所有Web API请求路由到一个控制器方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以自定义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.com/api/products/

www.mysite.com/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)

我首先研究了如何创建自定义的IHttpControllerSelectorIHttpActionSelector 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请求路由到一个控制器方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆