C# 在windows窗体的HttpClient类中使用DelegatingHandler-尚未设置内部处理程序
首先,我收到的错误消息如下:尚未设置内部处理程序 我正在编写一个自定义消息处理程序来处理API的身份验证cookie超时。例如,如果我的代码库调用API,然后又收到401,那么它应该重试登录url以获得更新的cookie。我计划按如下方式完成这项工作:C# 在windows窗体的HttpClient类中使用DelegatingHandler-尚未设置内部处理程序,c#,asp.net-web-api,dotnet-httpclient,C#,Asp.net Web Api,Dotnet Httpclient,首先,我收到的错误消息如下:尚未设置内部处理程序 我正在编写一个自定义消息处理程序来处理API的身份验证cookie超时。例如,如果我的代码库调用API,然后又收到401,那么它应该重试登录url以获得更新的cookie。我计划按如下方式完成这项工作: public class CkApiMessageHandler : DelegatingHandler { private readonly string _email; private readonly string _pas
public class CkApiMessageHandler : DelegatingHandler
{
private readonly string _email;
private readonly string _password;
private const string _loginPath = "Account/Login";
public CkApiMessageHandler(string email, string password)
{
_email = email;
_password = password;
//InnerHandler = new HttpControllerDispatcher(null);
}
protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var response = await base.SendAsync(request, cancellationToken);
if(response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
{
Logging.Logger.LogInformation("Authentication cookie timed out");
var baseAddress = request.RequestUri.Host;
var loginPath = baseAddress + _loginPath;
var originalRequest = request;
var loginRequest = new HttpRequestMessage(new HttpMethod("POST"), loginPath);
var dict = new Dictionary<string, string>();
dict.Add("Email", _email);
dict.Add("Password", _password);
var form = new FormUrlEncodedContent(dict);
loginRequest.Content = form;
loginRequest.Headers.Clear();
foreach(var header in originalRequest.Headers)
{
loginRequest.Headers.Add(header.Key, header.Value);
}
var loginResponse = await base.SendAsync(loginRequest, cancellationToken);
if (loginResponse.IsSuccessStatusCode)
{
Logging.Logger.LogInformation("Successfully logged back in");
return await base.SendAsync(originalRequest, cancellationToken);
}
else
{
Logging.Logger.LogException(new Exception("Failed to log back in"), "Could not log back in");
}
}
return response;
}
}
所以我的问题是:如何让这个DelegatingHandler在web api项目的上下文之外完成它的工作
正在进行更新。看起来我可以只使用HttpClientHandler类
我应该早点意识到这一点,但是将内部处理程序设置为
HttpClient
使用的默认处理程序是有意义的。因此,在DelegatingHandler
的子类中,您应该将内部处理程序设置为HttpClient
使用的默认处理程序,如下所示:
public CkApiMessageHandler(string email, string password, Guid moduleId)
{
_email = email;
_password = password;
_moduleId = moduleId;
InnerHandler = new HttpClientHandler();
}
或者您可以使用HttpClientFactory
_client = HttpClientFactory.Create(new CKEnterprise.Common.CkApiMessageHandler(email, password))
阿德里安的回答是正确的。您必须为自定义处理程序设置内部处理程序,但是有更好的方法来设置内部处理程序
public MyDelegatingHandler( ) : base( new HttpClientHandler( ) )
这完全不是直觉。好发现:)这对我来说更有意义。谢谢Raj
_client = HttpClientFactory.Create(new CKEnterprise.Common.CkApiMessageHandler(email, password))
public MyDelegatingHandler( ) : base( new HttpClientHandler( ) )