来自DelegatingHandler的“无法多次发送相同的请求消息”错误

时间:2019-04-09 20:26:58

标签: c# httpclient delegatinghandler

我不确定这段代码有什么问题。有人可以帮我为什么我在运行这段代码时看到错误吗?

这是我的处理程序代码:

public class TestHandler1 : DelegatingHandler
    {
        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            HttpClient client = new HttpClient();// Creating a client and calling destination url. I dont want to call base.SendAsync(request) because I dont want to go next handler or controller. Not sure if this is the problem here.
            return await client.SendAsync(request);
        }
    }

当我运行UT时,我看到错误“ System.InvalidOperationException:请求消息已发送。无法多次发送相同的请求消息。”

[TestMethod]
        public async Task TestHandler()
        {
            TestHandler1 testHandler = new TestHandler1();

            HttpClient httpClientForTest = new HttpClient(testHandler);
            var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "http://1.1.1.1/App/Service");
            var response = await httpClientForTest.SendAsync(httpRequestMessage);
            Assert.IsTrue(response.IsSuccessStatusCode);
        }

0 个答案:

没有答案