我有一个winforms客户端应用程序,它使用HttpClient
连接到WebApi2应用程序。我目前正在本地测试,因此服务器开始使用IIS Express 10。
服务器应用程序允许匿名和Windows身份验证。每个控制器都具有Authorize
属性。
HttpClient
的设置如下:
WebRequestHandler handler = new WebRequestHandler()
{
AllowAutoRedirect = false,
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate,
CookieContainer = cookieContainer,
Credentionals = new NetworkCredential(username, password),
UseCookies = true,
UseDefaultCredentials = true,
UseProxy = false,
};
client = new HttpClient(handler, true)
{
BaseAddress = new Uri(myUrl)
};
为了确保,我也这样做:
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", Credentials.UserName, Credentials.Password))));
应用程序运行正常,但以下是IIS Express生成的日志片段:
10:51:11 :: 1 POST / myserver / Login - 55567 - :: 1 - - 401 0 0 389
10:51:17 :: 1 POST / myserver / Login - 55567 MicrosoftAccount \ myemail@here.com :: 1 - - 200 0 0 5760
10:51:51 :: 1 POST / myserver / SearchFor itemType = 38 55567 - :: 1 - - 401 0 0 347
10:51:52 :: 1 POST / myserver / SearchFor itemType = 38 55567 MicrosoftAccount \ myemail@here.com :: 1 - - 200 0 0 815
10:51:55 :: 1 GET / myserver / CustomerType / 174 - 55567 - :: 1 - - 401 0 0 400
10:51:55 :: 1 GET / myserver / CustomerType / 174 - 55567 MicrosoftAccount \ myemail@here.com :: 1 - - 200 0 0 574
对于每个请求,都有401
然后是'200'代码。发送请求时,我没有明确设置WWW-Authenticate
标头。
如何确定服务器向客户端发送何种质询?
修改
我已将HttpClient
的初始化更改为:
var uri = new Uri(myUrl);
var credentialCache = new CredentialCache();
credentialCache.Add(new Uri(uri.GetLeftPart(UriPartial.Authority)), "NTLM", credentials);
WebRequestHandler handler = new WebRequestHandler()
{
AuthenticationLevel = AuthenticationLevel.MutualAuthRequested,
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate,
Credentials = credentialCache,
PreAuthenticate = true,
};
client = new HttpClient(handler, true)
{
BaseAddress = uri
};
在GET
次请求中,我总是收到401
后跟200
个回复。在其他请求(POST
,PATCH
)上,只有200
我假设客户端正确发送了身份验证标头。
为什么我仍在401
GET
次请求?