Asp.net 使用moq模拟HttpMessageHandler-如何获取请求的内容?

Asp.net 使用moq模拟HttpMessageHandler-如何获取请求的内容?,asp.net,async-await,integration-testing,moq,httpcontent,Asp.net,Async Await,Integration Testing,Moq,Httpcontent,在决定要为测试返回哪种响应之前,是否有办法获取http请求的内容?多个测试将使用该类,每个测试将有多个http请求。此代码不会编译,因为lambda不是异步的,并且其中存在等待。我不熟悉AsyncWait,所以我不知道如何解决这个问题。我曾短暂地考虑过拥有多个TestHttpClientFactorys,但这意味着代码会重复,所以如果可能的话,我决定不使用它。感谢您的帮助 public class TestHttpClientFactory : IHttpClientFactory {

在决定要为测试返回哪种响应之前,是否有办法获取http请求的内容?多个测试将使用该类,每个测试将有多个http请求。此代码不会编译,因为lambda不是异步的,并且其中存在等待。我不熟悉AsyncWait,所以我不知道如何解决这个问题。我曾短暂地考虑过拥有多个TestHttpClientFactorys,但这意味着代码会重复,所以如果可能的话,我决定不使用它。感谢您的帮助

public class TestHttpClientFactory : IHttpClientFactory
{
    public HttpClient CreateClient(string name)
    {
        var messageHandlerMock = new Mock<HttpMessageHandler>(MockBehavior.Strict);

        messageHandlerMock.Protected()
            .Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.IsAny<HttpRequestMessage>(), ItExpr.IsAny<CancellationToken>())
            .ReturnsAsync((HttpRequestMessage request, CancellationToken token) =>
            {
                HttpResponseMessage response = new HttpResponseMessage();
                var requestMessageContent = await request.Content.ReadAsStringAsync();

                // decide what to put in the response after looking at the contents of the request

                return response;
            })
            .Verifiable();

        var httpClient = new HttpClient(messageHandlerMock.Object);
        return httpClient;
    }
}
公共类TestHttpClientFactory:IHttpClient工厂
{
公共HttpClient CreateClient(字符串名称)
{
var messageHandlerMock=newmock(MockBehavior.Strict);
messageHandlerMock.Protected()
.Setup(“sendsync”、ItExpr.IsAny()、ItExpr.IsAny())
.ReturnsAsync((HttpRequestMessage请求,CancellationToken令牌)=>
{
HttpResponseMessage response=新的HttpResponseMessage();
var requestMessageContent=wait request.Content.ReadAsStringAsync();
//查看请求的内容后,决定在响应中放置什么
返回响应;
})
.可验证();
var httpClient=新的httpClient(messageHandlerMock.Object);
返回httpClient;
}
}

要利用异步委托,请改用
返回方法

public class TestHttpClientFactory : IHttpClientFactory {
    public HttpClient CreateClient(string name) {
        var messageHandlerMock = new Mock<HttpMessageHandler>(MockBehavior.Strict);

        messageHandlerMock.Protected()
            .Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.IsAny<HttpRequestMessage>(), ItExpr.IsAny<CancellationToken>())
            .Returns(async (HttpRequestMessage request, CancellationToken token) => {
                
                string requestMessageContent = await request.Content.ReadAsStringAsync();

                HttpResponseMessage response = new HttpResponseMessage();

                //...decide what to put in the response after looking at the contents of the request

                return response;
            })
            .Verifiable();

        var httpClient = new HttpClient(messageHandlerMock.Object);
        return httpClient;
    }
}

创建自己的处理程序,公开一个委托来处理所需的行为,这是一个好主意。如果MOQ不能工作,我一定会考虑。我还应该提到,我尝试过VaR请求消息。但是有一个System.NullReferenceException,所以这不是一个解决方案。请看一下我对类似问题的回答,谢谢。我决定对使用“Returns(async…”进行一次小而有效的更改,效果非常好!@rjacobsen0很高兴它成功了。编码愉快!!!
public class DelegatingHandlerStub : DelegatingHandler {
    private readonly Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> _handlerFunc;
    public DelegatingHandlerStub() {
        _handlerFunc = (request, cancellationToken) => Task.FromResult(request.CreateResponse(HttpStatusCode.OK));
    }

    public DelegatingHandlerStub(Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> handlerFunc) {
        _handlerFunc = handlerFunc;
    }

    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) {
        return _handlerFunc(request, cancellationToken);
    }
}
public class TestHttpClientFactory : IHttpClientFactory {
    public HttpClient CreateClient(string name) {
        var messageHandlerMock = new DelegatingHandlerStub(async (HttpRequestMessage request, CancellationToken token) => {
                
            string requestMessageContent = await request.Content.ReadAsStringAsync();

            HttpResponseMessage response = new HttpResponseMessage();

            //...decide what to put in the response after looking at the contents of the request

            return response;
        });

        var httpClient = new HttpClient(messageHandlerMock);
        return httpClient;
    }
}