我试图让委派工作使用WebClient(或HttpClient)调用webservice。我有一个带有控制器和Web Api控制器的MVC4 Web应用程序。我在Intranet的远程服务器上设置了应用程序,并且在本地计算机上运行同一应用程序,在两台计算机上使用IIS,并使用基本身份验证。代表不能正常工作
的网络API控制器很简单,这是服务的代码:
[Authorize(Users="domain\\username")]
[HttpPost]
[HttpGet]
public string GetSimulationTest()
{
return "WS successfully called";
}
此WS工作从我的浏览器或提琴手完全正常,本地和远程。
在我家的控制器,我有以下方法:
public ActionResult TestOwnWS()
{
ContentResult res = null;
WindowsIdentity wi = (WindowsIdentity)User.Identity;
WindowsImpersonationContext ctx = null;
try
{
ctx = wi.Impersonate();
WebClient wc = new WebClient();
wc.UseDefaultCredentials = true;
wc.Headers.Add("Content-Type", "application/xml");
res = this.Content(wc.DownloadString("linktoWS"), "application/xml");
}
catch (Exception e)
{
Response.Write(e.Message);
Response.End();
}
finally
{
ctx.Undo();
}
return res;
}
这里的问题:我上wc.DownloadString()调用401授权。如果我使用本地webservice而不是远程webservice,它甚至不会工作。但是,如果我使用wc.Credentials = new NetworkCredentials(user,pass,domain);
手动设置wc.Credentials,它就可以工作。
我以前使用Windows身份验证,但它仍然拒绝工作,所以我阅读委派,显然,它应该工作正常,如果两台计算机上的帐户是相同的(他们是)与基本身份验证,而Windows身份验证是更挑剔。
为什么它拒绝使用默认凭据,我仍然得到委派错误?我已经阅读了msdn文章,并且找不到我做错了什么。
我想出了一个解决方法(只要它是基本的身份验证),即运行'wc.Headers.Add(“Authorization”,Request.Headers [“Authorization”]);',但我会爱如果有人有更好的方法来解决这个问题,因为这个修正强制客户端和目标站点都运行基本身份验证。 – Tobberoth