对创建的上下文的响应不断给我NullStream

时间:2017-09-26 18:20:21

标签: .net-core middleware asp.net-core-2.0

我试图为批量请求编写中间件i .net core 2.0。 到目前为止,我已经拆分了请求,将每个请求传递给控制器​​。 控制器返回值,但由于某种原因,我解析到控制器的创建上下文的响应不断给我一个NullStream,所以我认为在我的设置中有一些我想念的东西。

代码如下所示:

var json = await streamHelper.StreamToJson(context.Request.Body);

var requests = JsonConvert.DeserializeObject<IEnumerable<RequestModel>>(json);

var responseBody = new List<ResponseModel>();

foreach (var request in requests)
{
    var newRequest = new HttpRequestFeature
    {
        Body = request.Body != null ? new MemoryStream(Encoding.ASCII.GetBytes(request.Body)) : null,
        Headers = context.Request.Headers,
        Method = request.Method,
        Path = request.RelativeUrl,
        PathBase = string.Empty,
        Protocol = context.Request.Protocol,
        Scheme = context.Request.Scheme,
        QueryString = context.Request.QueryString.Value
    };

    var newRespone = new HttpResponseFeature();
    var requestLifetimeFeature = new HttpRequestLifetimeFeature();

    var features = CreateDefaultFeatures(context.Features);
    features.Set<IHttpRequestFeature>(newRequest);
    features.Set<IHttpResponseFeature>(newRespone);
    features.Set<IHttpRequestLifetimeFeature>(requestLifetimeFeature);

    var innerContext = _factory.Create(features);
    await _next(innerContext);

    var responseJson = await streamHelper.StreamToJson(innerContext.Response.Body);

我不确定我在设置中缺少什么,因为innerContext.Response.Body没有设置。

我用于测试和被点击的端点之一就像这样

[Route("api/[controller]")]
public class ValuesController : Controller
{
    // GET api/values
    [HttpGet]
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }
}

1 个答案:

答案 0 :(得分:1)

我发现了错误或两个错误,无法正常工作。

首先,我必须将newResponse更改为

var newRespone = new HttpResponseFeature{ Body = new MemoryStream() };

由于HttpResponseFeature在构造函数中将Body设置为Stream.Null。

当完成后,Body在尝试阅读时保持空字符串。这是通过将位置设置为零来修复的,如

innerContext.Response.Body.Position = 0;