![](/img/trans.png)
[英]Why my web api return Status code 401 when i use WebClient class and Status code 200 when i use HttpWebResponse?
[英]401 when issuing a WebClient request in Web API
我希望机智的人能帮助我。
我有一个简单的Web API Web服务,该服务检查文档管理系统上是否存在工作区以确定安全性访问。
当我在浏览器中运行此服务时,它可以正常工作。 但是,当我尝试在另一个Web API应用程序中使用该服务时,它会给出401。
我已经尝试了几乎所有可以想到的东西,并且可以在这里找到。 它正在使用Windows身份验证,无论我尝试使用NTLM,“协商”还是“协商:Kerberos”,都不会通过当前用户的凭据。 如果我对用户名,密码和域进行硬编码,则可以正常工作。 代码如下
[HttpGet]
[Route("api/Session/CheckSecurity")]
public HttpResponseMessage CheckSecurity(string id)
{
WebClient client;
WindowsIdentity userId;
string result;
try
{
userId = (WindowsIdentity)User.Identity;
using (WindowsImpersonationContext context = userId.Impersonate())
{
client = new System.Net.WebClient() { UseDefaultCredentials = true };
client.Headers.Add("content-type", "application/json");
result = client.DownloadString(new Uri(String.Format(ConfigurationManager.AppSettings["Url"], id)));
return new HttpResponseMessage(HttpStatusCode.OK);
}
}
catch (WebException webExcp)
{
HttpWebResponse resp = (HttpWebResponse)webExcp.Response;
resp.Headers.Remove("WWW-Authenticate");
// return 403 instead of 401 to prevent security pop up
return new HttpResponseMessage(resp.StatusCode == HttpStatusCode.Unauthorized ? HttpStatusCode.Forbidden : resp.StatusCode);
}
catch (Exception ex)
{
return new HttpResponseMessage(HttpStatusCode.InternalServerError);
}
}
因此,经过两天的尝试之后,我想出了一切,并且将自己的头发从Google搜索中剔除,这导致我遇到了一个完全不相关的问题,即使用代理会导致身份验证问题。
这触发了一个啊哈! 此刻,我关闭了Fiddler。 瞧,一切都按预期进行了!
我不确定为什么会发生这种情况,但是我将与Fiddler合作,看看我是否可以在将来阻止这种情况的发生。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.