【问题标题】:Access denied to ASP.NET WebAPI on IIS拒绝访问 IIS 上的 ASP.NET WebAPI
【发布时间】:2017-04-28 23:15:49
【问题描述】:

我必须使用 ASP.NET 应用程序:一个是 Web API,另一个是向第一个发出请求的 MVC。

一切都在开发中工作(VS 与 IIS Express),但现在我将这两个应用程序发布到生产服务器,我无法使用 MVC 应用程序访问 api。

我在 API 上启用了 CORS:

var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);

在 MVC 应用程序上,我的 api 基本 url 设置为 https://localhost:44351/,然后在 IIS 中我有这个绑定(WEB Api 站点):

我可以使用 postman 向 API 发出请求,但是当我运行我的 MVC 应用程序时,我无法发出请求(同样,我可以在开发中发出请求)。

谢谢。

编辑

控制器代码示例(MVC):

        try
        {
            var client = WebApiHttpClient.GetClient();

            var response = await client.PostAsync("Token", content);
            if (response.IsSuccessStatusCode)
            {
                TokenResponse tokenResponse =
                await response.Content.ReadAsAsync<TokenResponse>();

                WebApiHttpClient.storeToken(tokenResponse);
                return RedirectToAction("Index", "Home");
            }
            else
            {
                return Content("response.StatusCode);
            }
        }
        catch
        {
            return Content("Error");
        }

我的 HttpClient 实现:

    public const string WebApiBaseAddress = "https://localhost:44351/";

    public static HttpClient GetClient()
    {
        HttpClient client = new HttpClient();
        client.BaseAddress = new Uri(WebApiBaseAddress);
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new
        MediaTypeWithQualityHeaderValue("application/json"));
        return client;
    }

编辑 2

InnerException 消息:

the underlying connection was closed could not establish trust relationship for the ssl/tls

【问题讨论】:

  • “不能提出请求”是什么意思?你会得到什么样的回应?
  • 您是如何提出请求的?按主机名或本地主机
  • 请查看编辑
  • 而且您不需要启用 CORS,因为您正在从同一个域发出请求。
  • SSL 证书存在问题。请看这篇帖子:stackoverflow.com/questions/703272/…

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


【解决方案1】:

只是总结一下 cmets 中的讨论。 问题是由于在 IIS 中为 Web API 应用程序使用了自签名证书。

这个问题的临时解决办法是在应用启动类(Global.asax)中加入这行代码:

ServicePointManager.ServerCertificateValidationCallback = ((sender, certificate, chain, sslPolicyErrors) => true);

当然,您不应该在生产中使用那行代码。在生产环境中,您应该有一个有效的 SSL 证书。

更多信息可以在这篇文章中找到: Could not establish trust relationship for SSL/TLS secure channel -- SOAP

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-27
    • 2023-03-22
    • 2020-10-09
    • 2016-10-30
    • 2013-05-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多