Route all Web API requests to one controller method

后端 未结 2 1182
死守一世寂寞
死守一世寂寞 2021-02-13 02:44

Is it possible to customize ASP.NET Web API\'s routing mechanism to route all requests to the API to one controller method?

If a request comes in to

www         


        
2条回答
  •  情话喂你
    2021-02-13 03:23

    I ran into a case where I needed to do this. (Web API 2)

    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
        }
    }
    

    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.

    The good thing about this is you can still use other controllers as well (as long as their routes don't start with "api/").

提交回复
热议问题