Return content with IHttpActionResult for non-OK response

前端 未结 15 2103
北恋
北恋 2020-11-28 17:55

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          


        
相关标签:
15条回答
  • 2020-11-28 18:43

    You can also do:

    return InternalServerError(new Exception("SOME CUSTOM MESSAGE"));
    
    0 讨论(0)
  • 2020-11-28 18:43

    @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;
        }
    }
    
    0 讨论(0)
  • 2020-11-28 18:46

    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.

    0 讨论(0)
  • 2020-11-28 18:47

    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();
        }
    
    0 讨论(0)
  • 2020-11-28 18:48

    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);
    
    0 讨论(0)
  • 2020-11-28 18:49

    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.

    0 讨论(0)
提交回复
热议问题