401在Web API中发出WebClient请求时

时间:2014-10-23 10:23:12

标签: c# asp.net-web-api

我希望有人可以帮助我,因为我在我的智慧中。结束。

我有一个简单的Web API Web服务,用于检查文档管理系统上是否存在工作空间以确定安全访问。

当我在浏览器中运行此服务时,它可以正常工作。但是,当我尝试在另一个Web API应用程序中使用该服务时,它会提供401.

我已经尝试了几乎所有我能想到的东西,并且可以在这里找到。它使用Windows身份验证,无论我尝试什么,NTLM,协商或协商:Kerberos,当前用户的凭据都不会通过。如果我硬编码我的用户ID,密码和域,但它的工作原理。代码在

之下
    [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);
        }
    }

1 个答案:

答案 0 :(得分:1)

因此,经过2天的尝试,我能想到并撕掉我的头发,谷歌搜索引发了一个完全不相关的问题,即使用代理会导致身份验证问题。

这引发了一场哈哈!那一刻,我关掉了提琴手。瞧,一切都按原样运作!

我不确定为什么会这样,但我会和Fiddler玩,看看我是否可以阻止这种情况发生。