Web Services HttpClientFactory Create方法在.Net Framework 4.8中不工作HttpClient正在工作

a64a0gku  于 2023-03-23  发布在  .NET
关注(0)|答案(1)|浏览(156)

我在.Net framework 4.8中开发了Web服务,httpRuntime targetFramework指向4.0。当我将targetFramework更改为4.8时,Http调用超时或返回403 Forbidden错误。但它与targetFramework 4.0一起工作。如果我使用HttpClient对象,它也可以工作。
不知道创建HttpClient对象与HttpClientFactory的主要区别是什么。Create()如果有人解决了这个问题或知道解决方案,请分享。提前感谢。

**配置(Web.config):**不工作

<httpRuntime targetFramework="4.8"/>

我用来调用API的代码(除了业务逻辑外,看起来很相似。)

public async Task<string> TestMethodAsync()
{    
    HttpClientWrapper clientWrapper = new HttpClientWrapper();
    HttpResponseMessage response = clientWrapper.GetAsync("https://www.google.com").Result;
    return response.Content.ReadAsStringAsync().Result;   
}

public class HttpClientWrapper
{
    private readonly CustomDelegatingHandler _delegatingHandler = new CustomDelegatingHandler();
    public async Task<HttpResponseMessage> GetAsync(string requestUri)
    {
        using (var client = HttpClientFactory.Create(_delegatingHandler))
        {
            return await client.GetAsync(requestUri);
        }
    }   
    public class CustomDelegatingHandler : DelegatingHandler
    {         
                  
    }
}
nzk0hqpo

nzk0hqpo1#

只要在使用awiat的地方添加ConfigureAwait(false)就解决了这个问题。

public async Task<string> TestMethodAsync()
{    
    HttpClientWrapper clientWrapper = new HttpClientWrapper();
    HttpResponseMessage response = clientWrapper.GetAsync("https://www.google.com").Result;
    return response.Content.ReadAsStringAsync().Result;   
}
public class HttpClientWrapper
{
    private readonly CustomDelegatingHandler _delegatingHandler = new CustomDelegatingHandler();
    public async Task<HttpResponseMessage> GetAsync(string requestUri)
    {
        using (var client = HttpClientFactory.Create(_delegatingHandler))
        {
            return await client.GetAsync(requestUri).ConfigureAwait(false);
        }
    }   
    public class CustomDelegatingHandler : DelegatingHandler
    {         
            
    }
}

从下面的博客中找到了解决方案,这里非常详细地解释了https://blog.stephencleary.com/2012/02/async-and-await.htmlhttps://blog.stephencleary.com/2012/07/dont-block-on-async-code.html

相关问题