Warm tip: This article is reproduced from serverfault.com, please click

其他-在IIS上启用CORS预检ASP.NET

(其他 - Enable CORS preflight ASP.NET on IIS)

发布于 2020-12-02 17:09:44

我仅具有ASP.NET应用程序的二进制文件,并且正在尝试将其在我的本地计算机上使用。我在尝试提出CORS时遇到了一些问题。

Access to XMLHttpRequest at 'http://xx.xx.xx.xx:8080/webapi/' from origin 
'http://xx.xx.xx.xx:8089' has been blocked by CORS policy: 
Response to preflight request doesn't pass access control check: 
No 'Access-Control-Allow-Origin' header is present on the requested resource.

我尝试了几件事,包括从这里https://www.iis.net/downloads/microsoft/iis-cors-module在IIS上安装CORS模块

我也尝试更改我的Web.Config以添加以下内容。我要做的就是让它开始工作,所以我希望允许所有请求通过。

<system.webServer>
  <cors enabled="true">
    <add origin="*" allowed="true" />
    <add origin="http://*" allowed="true" />
  </cors>

但我仍然遇到相同的错误。奇怪的是,webapi和ASP.NET客户端都在同一台计算机上的不同端口8080和8089上。

Questioner
p0tta
Viewed
11
Ding Peng 2020-12-03 11:20:21

首先,必须确保已成功安装cors模块,然后需要在应用程序的web.config中添加以下配置:

 <system.webServer> 
   <cors enabled="true">
    <add origin="*" allowed="true" />
  </cors>
  </system.webServer>

该配置节点在配置节点下。

如果仍然无法解决,你还可以通过向全局文件中添加以下代码来解决跨域问题:

protected void Application_BeginRequest(object sender, EventArgs e)
        {
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");

            if (HttpContext.Current.Request.HttpMethod == "OPTIONS")

            {
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "*");

                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "*");

                HttpContext.Current.Response.End();
            }

        }