【发布时间】:2013-12-05 17:58:30
【问题描述】:
我正在尝试让委派使用 WebClient(或 HttpClient )调用 Web 服务。我有一个带有控制器和 Web Api 控制器的 MVC4 Web 应用程序。我在 Intranet 上的远程服务器上设置了应用程序,并且我在本地计算机上运行相同的应用程序,在两台计算机上使用 IIS,并使用基本身份验证。
Web 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 Unauthorized。如果我使用本地 web 服务而不是远程 web 服务,它甚至都不起作用。但是,如果我使用 wc.Credentials = new NetworkCredentials(user,pass,domain); 手动设置 wc.Credentials 则可以。
我之前使用过 Windows 身份验证,但它仍然拒绝工作,所以我阅读了委托,显然,如果两台计算机(它们是)上的帐户相同且具有基本身份验证,而 Windows 身份验证更多,它应该可以正常工作挑剔。
为什么它拒绝使用默认凭据,我仍然得到委派错误吗?我已经阅读了有关它的 msdn 文章,但我找不到我做错了什么。
【问题讨论】:
-
我想出了一个解决方法(只要它是基本身份验证),即运行
wc.Headers.Add("Authorization", Request.Headers["Authorization"]);,但如果有人有更好的方法来解决这个问题,我会很高兴,因为这个修复会强制客户端和目标站点都运行基本身份验证。
标签: c# asp.net-mvc authentication iis asp.net-web-api