Multiple Get actions with different attribute rout

2019-07-29 20:16发布

问题:

If I design my controller in such a way:

public class ItemController : ApiController
{
    [HttpGet]
    [RoutePrefix("item/dosomething")]
    public void DoSomething(Item item)
    { }

    [HttpGet]
    [RoutePrefix("item/dosomethingnicer")]
    public void DoSomethingNicer(Item item)
    { }

    [HttpGet]
    [RoutePrefix("item/dosomethingelse")]
    public void DoSomethingElse(Item item)
    { }
}

Would this work?

回答1:

I would expect a structure more akin to this:

[RoutePrefix("item")]
public class ItemController : ApiController
{
    [HttpGet]
    [Route("dosomething")]
    public void DoSomething(Item item)
    { }

    [HttpGet]
    [Route("dosomethingnicer")]
    public void DoSomethingNicer(Item item)
    { }

    [HttpGet]
    [Route("dosomethingelse")]
    public void DoSomethingElse(Item item)
    { }
}


回答2:

I use Web Api 2 in this way in a lot of Controllers:

[HttpGet]
[Route("~/api/{version}/research/export")]
public IHttpActionResult Export(){
     do stuff...
} 

[HttpPost]
[Route("~/api/{version}/research/list")]
public IHttpActionResult List()
{
     do stuff...
}

I use full api path description and it works with no problems.