ASP.NET Web Api Routing Customization

前端 未结 4 1668
刺人心
刺人心 2021-02-19 11:38

I have WebApi controllers that end with the \"Api\" suffix in their names (For ex: StudentsApiController, InstructorsApiController). I do this to easily differentiate my MVC con

4条回答
  •  既然无缘
    2021-02-19 12:18

    Now that ASP.NET Web API 2 is out, there is a much less cumbersome way to do more complex routing like that you suggested, by using attribute routing.

    At the top of your controller just add the following attribute:

    [RoutePrefix("api/students")]
    public class StudentsApiController : ApiController
    {
        ...
    }
    

    And then before each API method:

    [Route("{id}"]
    public HttpResponseMessage Get(int id)
    {
        ...
    }
    

    There is a bit of setup required, but the positives of doing routing this way are many. For one, you can put the routing with the controllers and methods that do the actual work, so you're never searching around wondering if you have the right route. Secondly and more importantly, it's much easier to do more complex routing, like having the controller name different from the route name (like you want) or having very complex patterns to match against.

提交回复
热议问题