我想为Typed HttpClient添加一个HttClientHandler以便包括证书身份验证。我在互联网上找到的所有示例都是这样的:services.AddHttpClient<IMyService, MyService>() .ConfigurePrimaryHttpMessageHandler(() => { return new HttpClientHandler() { // Set here whatever you need to get configured }; });但是我不想在这里包含获取证书的所有逻辑,所以我想使用的通用版本ConfigurePrimaryHttpMessageHandler 并编写我自己的消息处理程序以将证书包括在请求中。问题是我在努力理解应该如何实现消息处理程序...我应该从 HttpClientHandler 继承吗?请帮助! 更新正如我最初怀疑的那样,并且@Nkosi确认,从HttpClient处理程序派生是在这种情况下的方法。最后的代码与此类似:public class MyHttpClientHandler : HttpClientHandler{ private readonly IMyConfiguration _myConfiguration; public MyHttpClientHandler(IMyConfiguration myConfiguration) { _myConfiguration = myConfiguration; using (var certStore = new X509Store(StoreName.My, StoreLocation.LocalMachine)) { certStore.Open(OpenFlags.ReadOnly); var certCollection = certStore.Certificates.Find( X509FindType.FindBySerialNumber, _myConfiguration.MyCertificateSerial, true); X509Certificate2 certificate = certCollection[0]; ClientCertificateOptions = ClientCertificateOption.Manual; SslProtocols = System.Security.Authentication.SslProtocols.Tls12; ClientCertificates.Add(certificate); } }} 非常重要! 另一方面,在尝试注册我的http客户端处理程序时,我注意到它从未被调用过。经过一番谷歌搜索后,我发现当前存在一个有关此问题的公开错误(https://github.com/aspnet/Extensions/issues/851)。因此,在解决该问题之前,您需要通过以下方式配置处理程序:services.AddTransient<MyHttpClientHandler>();services.AddHttpClient<IMyService, MyService>() .ConfigurePrimaryHttpMessageHandler(sp => sp.GetRequiredService<MyHttpClientHandler>()); (adsbygoogle = window.adsbygoogle || []).push({}); 最佳答案 从HttpClientHandler或任何HttpMessageHandler派生类派生。public class MyHttpClientHandler : HttpClientHandler { public MyHttpClientHandler() { //Set here whatever you need to get configured } //...override members as needed}使用适当的分机调用您的处理程序services .AddHttpClient<IMyService, MyService>() .ConfigurePrimaryHttpMessageHandler<MyHttpClientHandler>();MyHttpClientHandler将通过共享所构造的处理程序生命周期的作用域服务提供者进行解析。关于c# - 如何使用ConfigurePrimaryHttpMessageHandler泛型,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57875320/ (adsbygoogle = window.adsbygoogle || []).push({}); 10-09 22:04