【问题标题】:the remote server returned an error 403 forbidden远程服务器返回错误 403 禁止
【发布时间】:2017-12-13 14:54:07
【问题描述】:

我正在从 c# 代码调用 WebAPI 方法,我得到:

远程服务器返回错误 403 禁止

在本地机器上它运行良好,在我的开发服务器中我收到403 forbidden 错误。

WebClient wc = new WebClient();
string url = string.Empty;
if (Tag == "L") {
    url = ConfigurationSettings.AppSettings["MajraApi"].ToString();
}
var httpWebRequest = (HttpWebRequest) WebRequest.Create(url);
wc.UseDefaultCredentials = true;
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using(var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) {
    string json1 = "Some JSON String";
    streamWriter.Write(json1);
    streamWriter.Flush();
    streamWriter.Close();
}
httpWebRequest.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
var httpResponse = (HttpWebResponse) httpWebRequest.GetResponse();
using(var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
    var result = streamReader.ReadToEnd();
}

【问题讨论】:

  • 您的问题解决了吗?随意接受关闭主题的最佳答案

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


【解决方案1】:

您可能已经设置了身份验证以连接到生产中的服务器 iis,因此您必须定义凭据以允许访问 API。您不能保留默认凭据 System.Net.CredentialCache.DefaultCredentials

通过更改 IIS 中定义的 userNamepassword 替换第 14 行:

httpWebRequest.Proxy.Credentials = new NetworkCredential() {
     UserName = "userName";
     Password = "password";
     Domain = "mydomain"; // facultative
};

【讨论】:

    【解决方案2】:

    当您使用 DefaultCredentials 发送请求时,它表示当前用户,即执行应用程序的用户。在您的本地计算机中,可能是您的域用户,而在您的开发服务器上,它是为应用程序池设置的用户 - 它可能没有您尝试调用的 api 的权限。

    【讨论】:

    • 对不起,先生,我听不懂。这段代码我能做什么。
    • 代码似乎没有问题,这是权限问题。因此,您将此 c# 代码部署到您的开发服务器,并调用 Web api。这个 web api 在哪里以及它如何验证请求?
    【解决方案3】:

    您是否在 IIS 中将您的 WebApi 服务 .NET CLR 版本的应用程序池设置为:

    没有托管代码

    另外,您是否根据需要将 webapi 文件夹的 wwwroot 权限授予用户 IIS_IUSRS 以读取和写入甚至修改(甚至完全控制)。还要添加对 NETWORK SERVICE 的权限。

    还要检查这个: IIS_IUSRS and IUSR permissions

    【讨论】:

    猜你喜欢
    • 2019-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-05
    • 1970-01-01
    相关资源
    最近更新 更多