Search code examples
c#asp.net-web-api2asp.net-web-api-routing

WebAPI 2 : Default GET ALL is invoked with wrong parameter


I am using WebAPI 2 with EF and scaffolding webapi controllers from visual studio. Each controller is created with 4 default verbs (GET,PUT,DELETE,POST) and 5 actions. while there are two versions of GET action.

  1. IQueryable<entity> GetEntities ()
  2. Task<IHttpActionResult> GetEntity(GUID key) // default is int id but I changed to guid.

I am using attribute routing and route prefix for the controller. just some fancy keywords for better management of url. [RoutePrefix("api/v3/Company")]

Problem :

Ideally when a wrong parameter is sent in url, it should return error, but it is not raising error, instead it fall back to the action without parameter.while if I send a wrong GUID, it shows error.

Like if I call : http://localhost:8080/api/v3/Company/1f7dc74f-af14-428d-aa31-147628e965b2

it shows the right result.

when I call : http://localhost:8080/api/v3/Company/1f7dc74f-af14-428d-aa31-147628e96500 (wrong key)

it set back to GetEntity() function and shows all records

when I call: http://localhost:8080/api/v3/Company/1 (not a GUID length parameter)

it do the same and shows all records.

I am using attribute [Route("{id:guid}")]

Really appreciate if I can get some guidance on this!


Solution

  • It is most likely that the route is defaulting back to the convention-based mapping. You need to explicitly make apply the route attribute on actions to let the routing know that it is the default route got GET

    [RoutePrefix("api/v3/Company")]
    public class CompanyController : ApiController {
    
        //GET api/v3/Company
        [HttpGet]
        [Route("")] //Default Get
        public IQueryable GetEntities() { ... }
    
        //GET api/v3/Company/1f7dc74f-af14-428d-aa31-147628e965b2
        [HttpGet]
        [Route("{id:guid}")] // ALSO NOTE THAT THE PARAMETER NAMES HAVE TO MATCH
        public Task<IHttpActionResult> GetEntity(Guid id) { ... }
    
        //...other code removed for brevity
    }
    

    Make sure that attribute routing is enabled in the web api config

    config.MapHttpAttributeRoutes();