Search code examples
c#asp.net-web-apiasp.net-mvc-5asp.net-web-api-routing

How to call three get methods in one controller?


Hi I am developing webapi application and I have three GET methods in one controller. I am able to call 2 methods but third one I am not able to call.

Below are my methods I am able to call.

[HttpGet]
[Route("me")]
public HttpResponseMessage me()
{
    return Request.CreateResponse(HttpStatusCode.OK, "Get me");
}
URL:http://localhost:22045/api/user/me

[HttpGet]
public HttpResponseMessage getUser(int id)
{
    return Request.CreateResponse(HttpStatusCode.OK, "Get user");
}

URL: http://localhost:22045/api/user/1

I am not able to call below one.

[Route("user/{role}")]
public HttpResponseMessage Get(string role)
{
    return Request.CreateResponse(HttpStatusCode.OK, "Get me on role");
}

I want to call it like

http://localhost:22045/api/user/OptionalRoleParameter

May I get some help here? Any help would be appreciated.


Solution

  • Using attribute routes with route constraints should help differentiate the routes enough to avoid clashes

    First ensure that attribute routing is enabled.

    config.MapHttpAttributeRoutes();
    

    Then make sure that the controller has the necessary attribute

    [RoutePrefix("api/user")]
    public class UsersController : ApiController {
    
        //GET api/user/me
        [HttpGet]
        [Route("me")]
        public HttpResponseMessage me() {
            return Request.CreateResponse(HttpStatusCode.OK, "Get me");
        }
    
        //GET api/user/1
        [HttpGet]
        [Route("{id:int")] // NOTE the parameter constraint
        public HttpResponseMessage getUser(int id) {
            return Request.CreateResponse(HttpStatusCode.OK, "Get user");
        }   
    
        //GET api/user
        //GET api/user/OptionalRoleHere
        [HttpGet]
        [Route("{role?}")] //NOTE the question mark used to identify optional parameter
        public HttpResponseMessage Get(string role = null) {
            return Request.CreateResponse(HttpStatusCode.OK, "Get me on role");
        }
    }
    

    Source: Attribute Routing in ASP.NET Web API 2 : Route Constraints