44

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?

P.S. 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
    }
}
mfluehr
  • 2,832
  • 2
  • 23
  • 31
Sviatoslav V.
  • 671
  • 6
  • 18

1 Answers1

49

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.

MarredCheese
  • 17,541
  • 8
  • 92
  • 91
Chris Pratt
  • 232,153
  • 36
  • 385
  • 444
  • Can I use `[HttpGet]` for `[Route("get/{query}", Name="getWithPagination")]`? – Jack Oct 05 '20 at 14:09
  • 2
    @Jack according to this [source](https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/routing?view=aspnetcore-6.0#route-name) it's possible. – HellBaby Feb 14 '22 at 19:15
  • @ChrisPratt Chico? What do you think? – Jack Feb 24 '22 at 08:34
  • Is the code following code equivalent? (1) [Route("api/books")] [HttpGet] (2) [HttpGet("api/books")] because in (1) I also specificy the HTTP verb. – TheAnonymousModeIT Dec 26 '22 at 14:54