关于asp.net Web API:对飞行前的响应:尽管启用了CORS,“没有’允许访问控制的原点’”

Response to preflight: “No 'Access-Control-Allowed-Origin'” despite CORS-enabled

我在解决4号角飞行前请求未通过CORS访问控制检查的问题时遇到了麻烦:"否'Access-Control-Allowed-Origin'。 我能够从数据库成功获取数据,但无法发布/保存数据。 我在前端使用VS代码访问Visual Studio 2015后端。 我的Web Api控制器具有以下属性:

[EnableCors(origins:"*", headers:"*", methods:"*")]

1
2
3
4
5
6
    [HttpPost]
    public async Task<IHttpActionResult> Post([FromBody]Employee employee)
    {
        _repo.Create(employee);
        return Ok();
    }

…但是当提出请求时,我收到以下错误:

XMLHttpRequest cannot load http://localhost:54429/api/createEmployee/.
Response to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:4200' is therefore not allowed
access

在我的vs代码中,我的服务如下所示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
postEmployeeForm(employee: Employee): Observable{

    let body = JSON.stringify(employee);
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    let options       = new RequestOptions({ headers: headers });

    console.log('posting employee ' , employee);

    return this.http.post("http://localhost:54429/api/employees/", body, options)
                    .map(this.extractData)
                    .catch(this.handleError)


}

enter image description here

405从帖子中删除正文和选项后的响应。

enter image description here

不知道我在想什么。

网络配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <connectionStrings>
   
    <!---->
   
   
  </connectionStrings>
  </appSettings>
  <system.web>
   
    <compilation debug="true" targetFramework="4.6.1" />
    <httpRuntime targetFramework="4.6.1" />
  </system.web>
  <system.webServer>
    <!--<httpProtocol>
      <customHeaders>
       
       
       
      </customHeaders>
    </httpProtocol>-->
    <modules>
      <remove name="FormsAuthentication" />
    </modules>
    <handlers>
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
     
    </handlers>
  </system.webServer>
  <runtime>
   
      <dependentAssembly>
       
        <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
      </dependentAssembly>
      <dependentAssembly>
       
        <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
      </dependentAssembly>
      <dependentAssembly>
       
        <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
      </dependentAssembly>
      <dependentAssembly>
       
        <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
      </dependentAssembly>
      <dependentAssembly>
       
        <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
       
        <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
      </dependentAssembly>
      <dependentAssembly>
       
        <bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
      </dependentAssembly>
      <dependentAssembly>
       
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
       
        <bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
      </dependentAssembly>
      <dependentAssembly>
       
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
       
        <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE="Web" /optionInfer+" />
    </compilers>
  </system.codedom>
</configuration>


我设法重现了您的问题。对我有用的解决方案是替换Web.config的一部分。在system.webServer下,用以下内容添加或替换现有的块:

1
2
3
4
5
6
<handlers>
  <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
  <remove name="OPTIONSVerbHandler" />
  <remove name="TRACEVerbHandler" />
 
</handlers>

如果已经有正确的内容,请尝试将其删除,运行服务器,停止服务器,重新添加内容,然后再次运行服务器。我知道这听起来很奇怪,但我认为这才是最终为我解决的问题。祝好运。

更新1

现在我们在服务器端发生了一些事情,请尝试删除Angular代码中的Content-Type标头和JSON.stringify内容。即:

1
2
3
4
5
6
7
postEmployeeForm(employee: Employee): Observable{
    console.log('posting employee ' , employee);

    return this.http.post("http://localhost:54429/api/employees/", employee)
        .map(this.extractData)
        .catch(this.handleError)
}

更新#2

我认为您的IIS Express配置可能会覆盖我们所做的某些更改。关闭Visual Studio,在Windows资源管理器中删除解决方案根目录下的.vs/config文件夹,然后尝试重新运行该项目。这应该重置您的IIS Express设置。如果您不完全满意删除该文件夹,只需对其重命名并执行相同的过程即可。

更新#3

我设法使您的示例项目运行。它演示了CORS的问题,但是通过使用我最初添加config.EnableCors的建议,此问题得以解决:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services
        config.EnableCors();

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name:"DefaultApi",
            routeTemplate:"api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}


问题似乎出在服务器端。

在任何非简单的CORS请求之前,浏览器都会发送OPTIONS预检请求,以确保此服务器允许非简单的CORS请求。 (带有application / json的POST请求并不简单)

在您的情况下,正如错误所暗示的那样,仅当对预检OPTIONS请求的响应包含值为'http:// localhost:4200'的access-control-allow-origin头时,才会发送原始POST请求。 (屏幕快照中的响应不包含此标题)

您没有写太多关于服务器实现的文章,但是如果您使用asp.net-web-api,这是一个简单的(有点棘手的)解决方案,说明如何使其响应这些预检OPTIONS请求-链接(另请参见注释)马库斯·坎宁安(Marcus Cunningham)


这都是关于服务器端配置的。为了进行开发方面的测试,您可以使用Google chrome及其插件。

https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=zh-CN

希望对您有所帮助。