在.NET核心中返回HttpResponseMessage时出错

时间:2019-09-12 06:00:53

标签: c# .net asp.net-mvc stream httpresponsemessage

我有一个简单的API网关控制器,该控制器返回一个IActionResult。问题是我无法阅读回复的正文。

如果我注释掉ExecuteResultAsync中的using块,它似乎可以正常工作,但是没有内容/正文。

不确定如何将其与返回的httpbody一起使用。返回HttpResponseMessage的RouteRequest是不可选项,因为它将来自微服务的响应作为来自网关的响应的正文。

因此,我需要使用HttpResponseMessageResult中间件,该中间件对于标头可正常工作,但对于正文则不起作用。

public async Task<IActionResult> RouteRequest()
{
    // Calls a method which send a request and gets a response and constructs a HttpResponseMessage         
    _contextAccessor.HttpContext.Response.RegisterForDispose(response);    
    return new HttpResponseMessageResult(response);        
}       


public class HttpResponseMessageResult : IActionResult
{
    private readonly HttpResponseMessage _responseMessage;

    public HttpResponseMessageResult(HttpResponseMessage responseMessage)
    {
        _responseMessage = responseMessage;
    }

    public async Task ExecuteResultAsync(ActionContext context)
    {
        context.HttpContext.Response.StatusCode = (int)_responseMessage.StatusCode;

        var responseMessageHeadersArray = _responseMessage.Headers.ToArray();
        for (int i = 0; i < responseMessageHeadersArray.Length; i++)
        {
            var header = responseMessageHeadersArray[i];
            context.HttpContext.Response.Headers.TryAdd(header.Key, new StringValues(header.Value.ToArray()));
        }

        using (var stream = await _responseMessage.Content.ReadAsStreamAsync())
        {
            await stream.CopyToAsync(context.HttpContext.Response.Body);
            await context.HttpContext.Response.Body.FlushAsync();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

根据this good answer,尝试类似的问题,我使用ObjectResult类,而不是手动操作流。当使用来自我们的API(JSON)之一的响应来运行它时,当objectResult调用ExecuteAsync时,在public class HttpResponseMessageResult : IActionResult { private readonly HttpResponseMessage _responseMessage; public HttpResponseMessageResult(HttpResponseMessage responseMessage) { _responseMessage = responseMessage; } public async Task ExecuteResultAsync(ActionContext context) { var objectResult = new ObjectResult(await _responseMessage.Content.ReadAsStreamAsync()) {StatusCode = (int)_responseMessage.StatusCode}; foreach (KeyValuePair<string, IEnumerable<string>> h in _responseMessage.Headers) { context.HttpContext.Response.Headers.TryAdd(h.Key, string.Join("", h.Value)); } await objectResult.ExecuteResultAsync(context); } } 主体中得到的数据量与初始响应中的数据量相同。

ex.Message