在DefaultHttpContext上使用FeatureCollection时,响应对象为null [英] Response object is null when using FeatureCollection on the DefaultHttpContext

查看:44
本文介绍了在DefaultHttpContext上使用FeatureCollection时,响应对象为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在测试某些.net Core中间件,并且希望在整个asp.net Core http管道中运行该中间件,而不是对其进行模拟.

I am testing some .net Core middleware and would like to run the middleware with the whole asp.net Core http pipeline instead of mocking it.

问题是当我使用功能部件集合时,不知道在HTTPRequest中未设置Response对象,并且该对象仅在Request本身上是只读的.

The problem is that somehow the Response object is not being set in the httpRequest when I use the Feature Collection and it is read only on the Request itself.

此代码在尝试写入响应流时会引发异常.

This code throws an exception when it tries to write to the Response Stream.

var fc = new FeatureCollection();
fc.Set<IHttpRequestFeature>(new HttpRequestFeature {
    Headers = new HeaderDictionary { { "RandomHeaderName", "123" } }
});
var httpContext = new DefaultHttpContext(fc);

var middleware = new RequestValidationMiddleware(
    next: async (innerHttpContext) =>
    {
        await innerHttpContext.Response.WriteAsync("test writing");
    });

middleware.InvokeAsync(httpContext).GetAwaiter().GetResult();

推荐答案

使用自定义功能集合,可以排除 DefaultHttpContext

By using a custom feature collection, you are excluding features that would have been added by the default constructor of the DefaultHttpContext

public DefaultHttpContext()
    : this(new FeatureCollection())
{
    Features.Set<IHttpRequestFeature>(new HttpRequestFeature());
    Features.Set<IHttpResponseFeature>(new HttpResponseFeature());
    Features.Set<IHttpResponseBodyFeature>(new StreamResponseBodyFeature(Stream.Null));
}

public DefaultHttpContext(IFeatureCollection features)
{
    _features.Initalize(features);
    _request = new DefaultHttpRequest(this);
    _response = new DefaultHttpResponse(this);
}

还通过添加执行测试所需的必需功能来尝试重新创建默认构造函数中的操作

try recreating what was done in the default constructor by also adding the required features needed to exercise your test

var fc = new FeatureCollection();
fc.Set<IHttpRequestFeature>(new HttpRequestFeature {
    Headers = new HeaderDictionary { { "RandomHeaderName", "123" } }
});
//Add response features
fc.Set<IHttpResponseFeature>(new HttpResponseFeature());
var responseBodyStream = new MemoryStream();
fc.Set<IHttpResponseBodyFeature>(new StreamResponseBodyFeature(responseBodyStream ));

var httpContext = new DefaultHttpContext(fc);

这篇关于在DefaultHttpContext上使用FeatureCollection时,响应对象为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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