Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return content with IHttpActionResult for non-OK response

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?

like image 814
mayabelle Avatar asked Feb 18 '15 16:02

mayabelle


People also ask

What is the return type of IHttpActionResult?

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 ActionResult and IHttpActionResult?

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.".


2 Answers

You can use this:

return Content(HttpStatusCode.BadRequest, "Any object"); 
like image 62
Shamil Yakupov Avatar answered Sep 21 '22 14:09

Shamil Yakupov


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.

like image 26
user1620220 Avatar answered Sep 23 '22 14:09

user1620220