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
You can also do:
return InternalServerError(new Exception("SOME CUSTOM MESSAGE"));
@mayabelle you can create IHttpActionResult concrete and wrapped those code like this:
public class NotFoundPlainTextActionResult : IHttpActionResult
{
public NotFoundPlainTextActionResult(HttpRequestMessage request, string message)
{
Request = request;
Message = message;
}
public string Message { get; private set; }
public HttpRequestMessage Request { get; private set; }
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
return Task.FromResult(ExecuteResult());
}
public HttpResponseMessage ExecuteResult()
{
var response = new HttpResponseMessage();
if (!string.IsNullOrWhiteSpace(Message))
//response.Content = new StringContent(Message);
response = Request.CreateErrorResponse(HttpStatusCode.NotFound, new Exception(Message));
response.RequestMessage = Request;
return response;
}
}
In ASP.NET Web API 2, you can wrap any ResponseMessage
in a ResponseMessageResult:
public IHttpActionResult Get()
{
HttpResponseMessage responseMessage = ...
return new ResponseMessageResult(responseMessage);
}
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.
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
public sealed class EmptyResult : IHttpActionResult
{
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
return Task.FromResult(new HttpResponseMessage(System.Net.HttpStatusCode.NoContent) { Content = new StringContent("Empty result") });
}
}
2) Create custom controller with new method:
public class CustomApiController : ApiController
{
public IHttpActionResult EmptyResult()
{
return new EmptyResult();
}
}
And then i can call them in my controllers, like this:
public IHttpActionResult SomeMethod()
{
return EmptyResult();
}
this answer is based on Shamil Yakupov answer, with real object instead of string.
using System.Dynamic;
dynamic response = new ExpandoObject();
response.message = "Email address already exist";
return Content<object>(HttpStatusCode.BadRequest, response);
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.