Search code examples
routesasp.net-web-apiasp.net-web-api-routing

using Web API attribute routing and RoutePrefix


When using web api, how does one call the proper routing methods if you use [RoutePrefix()]

Say you have something like "MyReallyLongNamedClassController". the default route would be http:...com/api/MyReallyLongNamedClass. The application then goes by methods named Get, Post, Put, etc (unless of course using verb decorators).

If I put a route prefix decorator of [RoutePrefix("api/LongClass")] on my controller, how can I have web api still use the defaults for the methods?

Meaning, I want the method named "GetAll()" to still map to "api/LongClass" (when using a get header) and "PostThis(int id)" to still map to "api/LongClass/{id}" (when using a post header)


Solution

  • Here's what I did to solve the problem without having to decorate all methods with annotations. I put RoutePrefix at the class level, as well as the default Route

    [RoutePrefix("api/longclass")]
    [Route("{id?}")]
    public class MyReallyLongNamedClass: ApiController
    {
    
        public string GetAll(int id)
        { 
            return "result";
        }
    
    
        public string PostThis([FromBody] MyModel model)
        {
           var res=  _repository.Save(model);
           return res;
        }
    }