【问题标题】:How can I read the Body of the DefaultHttpContext? [duplicate]如何阅读 DefaultHttpContext 的正文? [复制]
【发布时间】:2021-10-16 13:24:15
【问题描述】:

我正在编写一个在其调用中使用DefaultHttpContext 的测试(startup 是这里的测试主题):

[Fact]
public async void HandleCabinet_ShouldReturnValidCabinetSettings()
{
    var startup = new Startup();
    var context = DefaultHttpConext();

    await startup.HandleCabinet(context);

    string body;
    using (var reader = new StreamReader(context.Response.Body, Encoding.UTF8))
    {
        body = reader.ReadToEnd();
    }

    Assert.Equal("some expectation", body);
}

问题是,body 始终是一个空字符串。在HandleCabinet 方法中,我这样写了一些东西:

await context.Response.WriteAsync("some expectation");

我看到默认情况下,BodyNullStream,所以我尝试设置这样的流:

context.Response.Body = new BufferedStream(new MemoryStream());

但是,这没有效果。

那么,我该如何构造DefaultHttpContext,以便我可以测试响应?

【问题讨论】:

    标签: c# asp.net-core httpcontext


    【解决方案1】:

    您可以使用 MemoryStream 并将位置重置为 0。

    例如

    创建DefaultHttpContext

    private DefaultHttpContext CreateHttpContext()
    {
        var context = new DefaultHttpContext
        {
            Response =
            {
                Body = new MemoryStream()
            }
        };
        return context;
    }
    

    正文到字符串:(注意:C# 9 语法)

    public static string StreamToString(Stream stream)
    {
        stream.Position = 0;
        using StreamReader reader = new(stream, Encoding.UTF8);
        return reader.ReadToEnd();
    }
    

    断言:

    var body = StreamToString(context.Response.Body);
    Assert.Equal("some expectation", body);
    

    我用来创建DefaultHttpContext的设置

    【讨论】:

      猜你喜欢
      • 2013-01-06
      • 1970-01-01
      • 2021-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-24
      • 2023-03-30
      相关资源
      最近更新 更多