使用 IHttpActionResult 为非 OK 响应返回内容 [英] Return content with IHttpActionResult for non-OK response

查看:22
本文介绍了使用 IHttpActionResult 为非 OK 响应返回内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于从 Web API 2 控制器返回,如果响应正常(状态 200),我可以返回带有响应的内容,如下所示:

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);
    }

如果可能,我想在可能的情况下使用内置的结果类型:https://msdn.microsoft.com/en-us/library/system.web.http.results(v=vs.118).aspx

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

我的问题是,对于另一种类型的响应(不是 200),我如何用它返回消息(字符串)?例如,我可以这样做:

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();
    }

但不是这个:

    public IHttpActionResult Get()
    {
       return InternalServerError("Message describing the error here");
    }

理想情况下,我希望对此进行概括,以便我可以使用 IHttpActionResult 的任何实现发回消息.

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);
    }

或者有更好的方法吗?

推荐答案

我最终采用了以下解决方案:

I ended up going with the following solution:

public class HttpActionResult : IHttpActionResult
{
    private readonly string _message;
    private readonly HttpStatusCode _statusCode;

    public HttpActionResult(HttpStatusCode statusCode, string message)
    {
        _statusCode = statusCode;
        _message = message;
    }

    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        HttpResponseMessage response = new HttpResponseMessage(_statusCode)
        {
            Content = new StringContent(_message)
        };
        return Task.FromResult(response);
    }
}

... 可以这样使用:

... which can be used like this:

public IHttpActionResult Get()
{
   return new HttpActionResult(HttpStatusCode.InternalServerError, "error message"); // can use any HTTP status code
}

我愿意接受改进建议.:)

I'm open to suggestions for improvement. :)

这篇关于使用 IHttpActionResult 为非 OK 响应返回内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆