gpt4 book ai didi

c# - 委托(delegate)不起作用

转载 作者:太空宇宙 更新时间:2023-11-03 16:04:07 25 4
gpt4 key购买 nike

我正在尝试让委托(delegate)工作以使用 WebClient(或 HttpClient 就此而言)调用 Web 服务。我有一个带有 Controller 和 Web Api Controller 的 MVC4 Web 应用程序。我在 Intranet 的远程服务器上设置了应用程序,并在本地计算机上运行相同的应用程序,在两台计算机上都使用 IIS,并使用基本身份验证。

Web Api Controller 很简单,这是服务的代码:

[Authorize(Users="domain\\username")]
[HttpPost]
[HttpGet]
public string GetSimulationTest()
{
return "WS successfully called";
}

这个 WS 在我的浏览器或 fiddler 上工作得很好,无论是本地还是远程。

在我的家庭 Controller 中,我有以下方法:

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。如果我使用本地网络服务而不是远程网络服务,它甚至不起作用。但是,如果我使用 wc.Credentials = new NetworkCredentials(user,pass,domain); 手动设置 wc.Credentials,它会起作用。

我之前使用过 Windows 身份验证,但它仍然无法工作,所以我阅读了有关委派的内容,显然,如果两台计算机上的帐户(它们是)相同且使用基本身份验证,那么它应该可以正常工作,而 Windows 身份验证则更多挑剔。

为什么它拒绝使用默认凭据,我还是弄错了委派吗?我已经阅读了有关它的 msdn 文章,但找不到我做错了什么。

最佳答案

Authorize 是一个过滤器,允许某些用户访问操作方法。

WindowsIdentity wi = (WindowsIdentity)User.Identity;

以上代码仍然获取登录用户的身份。模拟不是执行此操作的正确方法。模拟代码要求您使用模拟用户登录,并获取带有句柄的 Windows 身份。

MSDN Link

最好的方法是使用您提到的 NetworkCredentials。

关于c# - 委托(delegate)不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20118020/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com