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?
I would recommend reading this post. There are tons of ways to use existing HttpResponse as suggested, but if you want to take advantage of Web Api 2, then look at using some of the built-in IHttpActionResult options such as
or
Choose the right return type for Web Api Controllers
I had the same problem. I want to create custom result for my api controllers, to call them like
return Ok("some text");
Then i did this: 1) Create custom result type with singletone
2) Create custom controller with new method:
And then i can call them in my controllers, like this:
You can use this:
For exceptions, I usually do
In ASP.NET Web API 2, you can wrap any
ResponseMessage
in a ResponseMessageResult:In some cases this may be the simplest way to get the desired result, although generally it might be preferable to use the various results in System.Web.Http.Results.
Sorry for the late answer why don't you simple use
return BadRequest("your message");
I use it for all my
IHttpActionResult
errors its working wellhere is the documentation : https://msdn.microsoft.com/en-us/library/system.web.http.apicontroller.badrequest(v=vs.118).aspx