首页 > 解决方案 > WebException 响应未返回完整响应

问题描述

我在我的 Web API 服务(Windows Autheticated)中使用 WebClient 对我们的公司目录(Windows Autheticated)进行 HTTP 调用,以获取用户的配置文件。请看下文。

public string DownloadPage(string ntid)
    {
        var result = "";

        try
        {
            using (var client = new WebClient() {UseDefaultCredentials = true})
            {
                using (var stream = client.OpenRead($"{url}{urlParameter}{ntid}"))
                {
                    using (var reader = new StreamReader(stream))
                    {
                        result = reader.ReadToEnd();
                    }
                }
            }
        }
        catch (Exception ex)
        {
            log.Error(ex); 
        }

        log.Info(result);
        return result;
    }

该代码在本地和我们的测试环境中完美运行,但在我将其部署到生产环境时返回“500 内部服务器错误”。我根据GetResponse()的 500 internal server error 的解决方案解决了 500 错误。请参阅下面的代码。但是,我发现只有部分 html 被返回。我需要从代码或 IIS 中设置诸如正文长度或最大返回大小之类的东西吗?

 public string DownloadPage(string ntid)
    {
        var result = "";

        try
        {
            using (var client = new WebClient() {UseDefaultCredentials = true})
            {
                using (var stream = client.OpenRead($"{url}{urlParameter}{ntid}"))
                {
                    using (var reader = new StreamReader(stream))
                    {
                        result = reader.ReadToEnd();
                    }
                }
            }
        }
        catch (WebException webex)
        {
            //https://stackoverflow.com/questions/4098945/500-internal-server-error-at-getresponse
            var errResp = webex.Response;
            using (var stream = errResp.GetResponseStream())
            {
                using (var reader = new StreamReader(stream))
                {
                    result = reader.ReadToEnd();
                }
            }
        }
        catch (Exception ex)
        {
            log.Error(ex); 
        }

        log.Info(result);
        return result;
    }

标签: c#.netasp.net-web-apiwebclientwindows-authentication

解决方案


我认为您可以访问活动目录,这就是代码在本地运行但在 IIS 上应用程序池从无权访问的 ApplicationPoolIdentity 运行的原因。

转到应用程序池并将身份更改为您的帐户。这是一张图片供您参考:在此处输入图像描述


推荐阅读