被CORS策略阻止:“ Access-Control-Allow-Origin”标头包含多个值“ *,*”,但仅允许一个

时间:2019-05-15 11:41:48

标签: c# api .net-core cors

我有一个使用.net core 2.2的登录API,突然返回此错误:  从源“ https://hostname/users/authenticate”对“ https://domain”处XMLHttpRequest的访问已被CORS策略阻止:对预检请求的响应未通过访问控制检查:“ Access-Control-Allow-Origin” < strong>标头包含多个值'*,*',但只允许一个。

起初我收到此错误: 请求的资源上没有“ Access-Control-Allow-Origin”标头。

然后在web.config中,我将“添加名称=” Access-Control-Allow-Origin“ value =” *“” 放入下面的完整代码:

然后我收到一个新错误,我在本文中询问“标题包含多个值'*,*',但仅允许一个值。

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <location path="." inheritInChildApplications="false">
    <system.webServer>
      <directoryBrowse enabled="true" />
      <httpProtocol>
        <customHeaders>
          <add name="Access-Control-Allow-Origin" value="*" />
          <add name="Access-Control-Allow-Methods" value="GET,PUT,POST,DELETE,OPTIONS"/>
          <add name="Access-Control-Allow-Headers" value="Origin, Content-Type, Accept"/>
          <add name="Access-Control-Allow-Credentials" value="true" />
        </customHeaders>
      </httpProtocol>
      <rewrite>
        <rules>
          <rule name="Https ApiLogin Page"  stopProcessing="true">
            <match url="(.*)" />
            <conditions logicalGrouping="MatchAny">
              <add input="{SERVER_PORT_SECURE}" pattern="^0$" />
            </conditions>
            <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="Permanent" />
          </rule>
        </rules>
      </rewrite>
      <modules runAllManagedModulesForAllRequests="true">
        <remove name="WebDavModule" />
      </modules>
      <handlers>
        <remove name="OPTIONSVerbHandler" />
        <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
      </handlers>
      <aspNetCore processPath="dotnet" arguments=".\WebApi.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" />
    </system.webServer>
  </location>
</configuration>

这是我的:header Request 这是我的:Startup.cs

我需要做什么来解决“标头包含多个值'*,*',但只允许一个。”

1 个答案:

答案 0 :(得分:0)

您必须在api中添加核心策略

将此放在您的控制器顶部

[EnableCors("SiteCorsPolicy")]

这在您的StartUp.cs中

services.AddAuthorization(opts =>
        {
            opts.AddPolicy(
          name: ConstantPolicies.DynamicPermission,
          configurePolicy: policy =>
          {
              policy.RequireAuthenticatedUser();
              policy.Requirements.Add(new DynamicPermissionRequirement());
          });
        });