Return content with IHttpActionResult for non-OK r

2019-01-12 16:27发布

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?

15条回答
Summer. ? 凉城
2楼-- · 2019-01-12 16:46

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

return Ok() 

or

return NotFound()

Choose the right return type for Web Api Controllers

查看更多
聊天终结者
3楼-- · 2019-01-12 16: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();
    }
查看更多
倾城 Initia
4楼-- · 2019-01-12 16:51

You can use this:

return Content(HttpStatusCode.BadRequest, "Any object");
查看更多
啃猪蹄的小仙女
5楼-- · 2019-01-12 16:52

For exceptions, I usually do

 catch (Exception ex)
        {
            return InternalServerError(new ApplicationException("Something went wrong in this request. internal exception: " + ex.Message));
        }
查看更多
小情绪 Triste *
6楼-- · 2019-01-12 16:53

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.

查看更多
劫难
7楼-- · 2019-01-12 16:54

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 well

here is the documentation : https://msdn.microsoft.com/en-us/library/system.web.http.apicontroller.badrequest(v=vs.118).aspx

查看更多
登录 后发表回答