Neil Walker
Neil Walker

Reputation: 6858

webapi multiple methods in MapHttpRoute

Using route annotations in asp.net core I can do the following easily enough

[HttpGet("ByID/{id}")]
public int GetByID(int id)
{
    return 5;
}

[HttpGet("ByName/{id}")]
public string GetByName(string name)
{
    return "neil";
}

However, with the same methods in the controller how do you do it using the non-annotation way in the WebApiConfig file (i.e. .net framework), i.e. what do I add to the below to make it work for the above example.

config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

As a bonus, can somebody tell me how I would have the same URL map to two GET items differentiated only by type, e.g.

[HttpGet("{id}")]
[HttpGet("{name}")]

where one is an integer and one is a string - in other words the same as the above but without having to specify two separate url segments (ByID, ByName)?

Upvotes: 1

Views: 878

Answers (1)

Nkosi
Nkosi

Reputation: 247373

You can use route constraints to differentiate the actions for the same path.

[RoutePrefix("api/somepath")]
public class MyController : ApiController {

    //Matches GET api/somepath/5
    [HttpGet]
    [Route("{id:int}")]
    public int GetByID(int id) {
        return id;
    }

    //Matches GET api/somepath/neil
    [HttpGet]
    [Route("{name}")]
    public string GetByName(string name) {
        return name;
    }
}

Note the default is string which is why there is none on the second action.

Upvotes: 1

Related Questions