为什么请求发送两次?

时间:2016-07-13 11:09:09

标签: c# asp.net winforms asp.net-web-api2 dotnet-httpclient

我有一个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个回复。在其他请求(POSTPATCH)上,只有200我假设客户端正确发送了身份验证标头。

为什么我仍在401 GET次请求?

0 个答案:

没有答案