For returning from a Web API 2 controller, I can return content with the response if the response is OK (status 200) like this:
public IHttpActionResult Get() { string myResult = ... return Ok(myResult); }
If possible, I want to use the built-in result types here when possible: https://msdn.microsoft.com/en-us/library/system.web.http.results(v=vs.118).aspx
My question is, for another type of response (not 200), how can I return a message (string) with it? For example, I can do this:
public IHttpActionResult Get() { return InternalServerError(); }
but not this:
public IHttpActionResult Get() { return InternalServerError("Message describing the error here"); }
Ideally I want this to be generalized so that I can send a message back with any of the implementations of IHttpActionResult.
Do I need to do this (and build my own response message):
public IHttpActionResult Get() { HttpResponseMessage responseMessage = ... return ResponseMessage(responseMessage); }
or is there a better way?
IHttpActionResult contains a single method, ExecuteAsync, which asynchronously creates an HttpResponseMessage instance. If a controller action returns an IHttpActionResult, Web API calls the ExecuteAsync method to create an HttpResponseMessage. Then it converts the HttpResponseMessage into an HTTP response message.
What is the difference between IHttpActionResult and IActionresult ? "IActionResult is the new abstraction that should be used in your actions. Since Web API and MVC frameworks have been unified in ASP.NET Core, various IActionResult implementations can handle both traditional API scenarios.".
You can use this:
return Content(HttpStatusCode.BadRequest, "Any object");
You can use HttpRequestMessagesExtensions.CreateErrorResponse (System.Net.Http
namespace), like so:
public IHttpActionResult Get() { return ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Message describing the error here")); }
It is preferable to create responses based on the request to take advantage of Web API's content negotiation.
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