首页 > 解决方案 > 来自 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:请求消息已发送。不能多次发送相同的请求消息。”</p>

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

标签: c#httpclientdelegatinghandler

解决方案


推荐阅读