简体   繁体   English

.NET 6 CORS 策略在客户端被阻止 CORS

[英].NET 6 CORS policy blocked on Client side CORS

The client-side of my application is.NET6 and server-side web API is .NET 4.8.我的应用程序的客户端是 .NET6 和服务器端 web API 是 .NET 4.8。 When attempting to access server-side the following error is produced within the console of the browser:尝试访问服务器端时,在浏览器的控制台中会产生以下错误:

Access to fetch at 'https://localhost:12345/api/controller/method' from origin 'https://localhost:34564' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. CORS 策略阻止了从源“https://localhost:12345/api/controller/method”获取的访问权限:不存在“访问控制允许来源”header在请求的资源上。 If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。

Within my startup.cs I have the following code:在我的 startup.cs 中,我有以下代码:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Latest);

    // In production, the React files will be served from this directory
    services.AddSpaStaticFiles(configuration =>
    {
        configuration.RootPath = "ClientApp/build";
    });
    services.AddCors(options =>
    {
        options.AddPolicy("AllowSpecificOrigin",
            builder => builder.AllowAnyOrigin()
                       .AllowAnyMethod()
                       .AllowAnyHeader()
        );

    });
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();               
    }
    else
    {  
        app.UseHsts();
    }
    app.UseCors("AllowSpecificOrigin");
    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseSpaStaticFiles();
    app.UseRouting();
    app.UseSpa(spa =>
    {
        spa.Options.SourcePath = "ClientApp";

        if (env.IsDevelopment())
        {
            spa.UseReactDevelopmentServer(npmScript: "start");
        }
    });
}

CORS setting in 'WebAPIConfig.cs 'WebAPIConfig.cs 中的 CORS 设置

public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            var cors = new EnableCorsAttribute("*", "*", "*");
            config.EnableCors(cors);
            config.Filters.Add(new AuthorizationAttribute());
            config.MapHttpAttributeRoutes();
            // Web API routes
            GlobalConfiguration.Configuration.Formatters.Add(new FormMultipartEncodedMediaTypeFormatter());
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}/{other}",
                defaults: new { id = RouteParameter.Optional, other = RouteParameter.Optional }
            );            
        }
    }

I'm not sure why "AllowAnyOrigin()" does not work but I managed to bypass the issue with this code:我不确定为什么“AllowAnyOrigin()”不起作用,但我设法绕过了这段代码的问题:

// global cors policy
app.UseCors(x => x
    .AllowAnyMethod()
    .AllowAnyHeader()
    .SetIsOriginAllowed(origin => true) // allow any origin 
    .AllowCredentials());

And of course this needs to be in your API project code not the front end code.当然,这需要在您的 API 项目代码中,而不是前端代码中。

In order to resolve your CORS issue, you can do the following in your web.config file:为了解决您的CORS问题,您可以在 web.config 文件中执行以下操作:

Under <system.webServer> section, place the following to enable CORS globally in your project:<system.webServer>部分下,放置以下内容以在您的项目中全局启用 CORS:

<httpProtocol>
    <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Credentials" value="true"/>
        <add name="Access-Control-Allow-Headers" value="Content-Type" />
        <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, OPTIONS" />
    </customHeaders>
</httpProtocol>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM