RoutePrefix vs Route

前端 未结 2 749
无人共我
无人共我 2020-12-28 13:23

I understand that RoutePrefix doesn\'t add a route to the routing table by itself. On your actions you need to have a Route attribute declared. I a

相关标签:
2条回答
  • 2020-12-28 14:20

    Route prefixes are associated with routes by design in attribute routing.

    It is used to set a common prefix for an entire controller.

    If you read the release notes that introduced the feature you may get a better understanding of the subject.

    ASP.NET Web API 2

    Attribute routing

    ASP.NET Web API now supports attribute routing, thanks to a contribution by Tim McCall. With attribute routing you can specify your Web API routes by annotating your actions and controllers like this:

    [RoutePrefix("orders")] 
    public class OrdersController : ApiController 
    { 
        [Route("{id}")] 
        public Order Get(int id) { } 
        [Route("{id}/approve")] 
        public Order Approve(int id) { } 
    } 
    

    Attribute routing gives you more control over the URIs in your web API. For example, you can easily define a resource hierarchy using a single API controller:

    public class MoviesController : ApiController 
    { 
        [Route("movies")] 
        public IEnumerable<Movie> Get() { } 
        [Route("actors/{actorId}/movies")] 
        public IEnumerable<Movie> GetByActor(int actorId) { } 
        [Route("directors/{directorId}/movies")] 
        public IEnumerable<Movie> GetByDirector(int directorId) { } 
    } 
    

    What's New in ASP.NET Web API 2.1

    What's New in ASP.NET Web API 2.2

    A really good article on the subject

    ASP.NET 5 Deep Dive: Routing

    While no expert on the subject, here is my understanding of how this works.

    With attribute routing the framework inspects the route attribute on the actions of a controller in order to create route entries to add to the route table. So as long as you are using attribute routing you are going to be using the [RouteAttribute]. Without this attribute the action will default back to convention-based routing. The RoutePrefixAttribute is an extensibility point that allows you more control of how you define your routes/Urls. The release notes say as much.

    Other than my understanding and the last link provided, everything else was quoted from MS documentation.

    0 讨论(0)
  • 2020-12-28 14:26

    For an authoritative source, here are the descriptions from MSDN (emphasis mine).

    RouteAttribute

    Place on a controller or action to expose it directly via a route. When placed on a controller, it applies to actions that do not have any System.Web.Mvc.RouteAttribute’s on them.

    RoutePrefixAttribute

    Annotates a controller with a route prefix that applies to all actions within the controller.

    As you can see, the description for Route mentions exposing the action(s), but RoutePrefix does not.

    0 讨论(0)
提交回复
热议问题