简体   繁体   中英

What's the difference between two attribute-based routing approaches: HttpGet(“”) and Route(“”)?

I was looking for information about attribute-based routing and found that there are two different attributes one can use: HttpGet("") and Route("") . However, I can't find any information about what the difference is between them.

Does one of them exist in order to support old ASP versions, or this there a different reason?

PS My code might not be totally correct, because I have just started to learn ASP. If something is not clear, I will try to explain.

public class MyController : Controller
{
    // APPROACH 1
    [Route("api/books")]
    [HttpGet]
    public async List<Book> GetBooks() 
    {
        // Implementation
    }

    // APPROACH 2
    [HttpGet("api/books")]
    public async List<Book> GetBooks()
    {
        // Implementation
    }
}

Route is method unspecific, whereas HttpGet obviously implies that only GET requests will be accepted. Generally, you want to use the specific attributes: HttpGet , HttpPost , etc. Route should be used mostly on controllers to specify the base path for all actions in that controller. The one exception is if you're creating routes for exception handling / status code pages. Then, you should use Route on those actions, since requests via multiple methods could potentially be routed there.

I also have the same question and after some study below is my understanding. I am tagging along this question trying to confirm it:

  1. HTTP methods are some actions done on a particular piece of data, which can be retrieved using a route.
  2. The same action can be done on different data (from a route), and different action can be done on the same piece of data.
  3. However in the controller, the method that defines how a HTTP method should be applied to a data must be unique. There must be only one method for each combination of HTTP method / route. If multiple methods are defined then the HTTP request will fail, as it does not know which method to use.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM