Route all Web API requests to one controller method

后端 未结 2 1180
死守一世寂寞
死守一世寂寞 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:36

    I don't konw why you would want to do this and I certainly wouldn't recommend routing everything through one controller, however you could achieve this as follows. Assuming you are only ever going to have a resource with an optional id in your calls, add this to your WebApiConfig:

    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{resource}/{id}",
                defaults: new { controller = "SuperDuper", id = RouteParameter.Optional }
            );
        }
    }
    

    Then define your controller method as follows:

    public class SuperDuperController : ApiController
    {
        public IHttpActionResult Get(string resource, int? id = null)
        {
            return Ok();
        }
    }
    

    You would need to decide on an appropriate IHttpActionResult to return for each different type of resource.

    Alternatively using Attribute Routing, ensure that config.MapHttpAttributeRoutes() is present in your WebApiConfig and add the following attributes to your controller method:

    [RoutePrefix("api")]
    public class SuperDuperController : ApiController
    {
        [Route("{resource}/{id?}")]
        public IHttpActionResult Get(string resource, int? id = null)
        {
            return Ok();
        }
    }
    

提交回复
热议问题