Response object is null when using FeatureCollection on the DefaultHttpContext

眉间皱痕 提交于 2021-02-10 18:27:05

问题


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.

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

回答1:


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


来源:https://stackoverflow.com/questions/59565511/response-object-is-null-when-using-featurecollection-on-the-defaulthttpcontext

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!