I am new to Web Api programming and am working on a .Net Framework Web App for the first time. I am wrapping some of my objects in Web Api calls, and I was wondering whether these two methods of routing in my controllers had any differences? I don't want to start using one only to find out later that it has some drawbacks, etc.
The first method would be to specify the route before the class:
[Route("api/[controller]/[action]")]
public class SomeController : Controller {
[HttpGet("{parameter}")]
public Object SomeMethod(int parameter) { ... }
(...)
}
and the second method would be to specify the route before each method:
[Route("api/[controller]")]
public class SomeController : Controller {
[HttpGet("SomeMethod/{parameter}")]
public Object SomeMethod(int parameter) { ... }
(...)
}
I'm just not experienced enough to know what the differences are between these two blocks of code, and whether there are any other ways to go about this that are more efficient. Thanks!
I am also going to need to implement Post, Put, Delete, etc., in the future.
The difference between the two options is the presence of [action] in the template URL. So if you understand how [controller] works, it will be easy to understand [action] purpose too.
The first option ([Route("api/[controller]/[action]")]) is better when you don't want to bother yourself when you rename your action method. With this option, in the future if you rename your action method it will be automatically reflected in the URL. Actually you have api/some/somemethod as the URL but if you rename SomeMethod to MySuperSomeMethod, the new URL will be api/some/mysupersomemethod.
The second option uses [HttpGet("SomeMethod/{parameter}")] and the name of your action method is inside the template route. So if you rename SomeMethod to MySuperSomeMethod the generated URL will always be api/some/somemethod.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With