From this source: http://www.tutorialsteacher.com/webapi/action-method-return-type-in-web-api I got, that Action in Web API can return:
I know what each of this options does, but I am curious whether there is some best practise, for example always use IHttpActionResult as return type, because it is a superset of all other options.
Option 1: Returning void, Primitive type, Complex type
Pros:
Cons:
Option 2: Returning HttpResponseMessage
Pros:
Cons:
Option 3: Returning IHttpActionResult
Web API 2.0 introduced this.
Pros:
Cons:
Conclusion
As you can see each option has pros and cons. For me the pros of each option outweigh the cons. My choice is: Option 3. But it is not written in stone.
I use asp.net core
but principle is the same. Also, not saying this is the best way, but for me this is the setup that works pretty nice.
I always use IActionResult
as its most flexible for me. I can then have action methods completely unaware of DTO
s that my services (which action methods call) return. All i do is, more or less, something like this:
[CustomExceptionsFilter]
[CustomValidateModelFilter]
[Authorize(Roles="whatever")]
public IActionResult ActionMethod(params){
return Ok(this._myService.whatever());
}
This way, if you change DTO
that your service returns (which happens alot, especially in early development phases), i don' thave to touch my controller at all.
Also, i have pretty much unified way of returning things where my custom exception error filter catches all service layer custom exceptions like validation exception, operation exception, etc...
[UPDATE]
in filters you don't actually return in a traditional sense. You rather set your context.result
(which is of type IActionResult
). So, lets say my service throws my custom MyServiceOperationException("You cannot do that")
exception.
What i do in my exception filter is:
public override void OnException(ExceptionContext context)
{
if (context.Exception is MyServiceOperationException)
{
context.Result = new BadRequestObjectResult(new MyErrorResult(){
Message = context.Exception.Message,
Code=context.Exception.MyErrorCode }
);
}
}
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