Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTTP Attribute Same as Routing - ASP.Net Core API?

I am making an ASP.net core 2.0 Web API and have a method in my controller called

[HttpPost("Create")]
public void Create()
{
    //  var d = employee;
}

Does the HttpPost act as the same the [Route] attribute or do I need both?

like image 862
chobo2 Avatar asked Mar 08 '26 02:03

chobo2


1 Answers

For Asp.Net Core Web API you do not need both.

It acts the same as Route and is the advised approach. When using MVC with views you use Route and Http{Verb} together.

Documentation states...

When building a REST API, it's rare that you will want to use [Route(...)] on an action method. It's better to use the more specific Http*Verb*Attributes to be precise about what your API supports. Clients of REST APIs are expected to know what paths and HTTP verbs map to specific logical operations.

Reference Routing to Controller Actions in ASP.NET Core

I would also advise having your actions return IActionResult to allow the proper HTTP Verb to be returned from the action.

[HttpPost("Create")]
public IActionResult Create() {
    //  var d = employee;
    return Ok();
}

void actions always return 200 OK unless an exception is thrown. This limits the possible response from the action.

like image 109
Nkosi Avatar answered Mar 10 '26 14:03

Nkosi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!