跨域请求被阻止:即使在我的 API 上启用 CORS 后也会发生;

IT技术 javascript c# .net reactjs cors
2021-05-12 03:51:20

在我的react应用程序中,这将显示。当我尝试发出帖子请求时。我在后端使用 .net core 2.2 webapi。

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:5050/api/Users. (Reason: missing token ‘access-control-allow-origin’ in CORS header ‘Access-Control-Allow-Headers’ from CORS preflight channel).[Learn More]
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:5050/api/Users. (Reason: CORS request did not succeed).[Learn More]

在我的 .net 核心 webapi 中。我也启用了 cors。使用IServiceCollection services

    services.AddCors(options =>
    {
        options.AddPolicy("AllowAll",
            builder =>
            {
                builder
                .AllowAnyOrigin() 
                .AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials();
            });
    });

IApplicationBuilder app

app.UseCors("AllowAll");

我也在控制器中使用了它。

[EnableCors("AllowAll")]

编辑:在调试控制台输出上。

    info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request starting HTTP/1.1 OPTIONS http://localhost:5050/api/Users  
    Request starting HTTP/1.1 OPTIONS http://localhost:5050/api/Users  
info: Microsoft.AspNetCore.Routing.EndpointMiddleware[0]
    Executing endpoint '405 HTTP Method Not Supported'
Microsoft.AspNetCore.Routing.EndpointMiddleware:Information: Executing endpoint '405 HTTP Method Not Supported'
info: Microsoft.AspNetCore.Routing.EndpointMiddleware[1]
    Executed endpoint '405 HTTP Method Not Supported'
Microsoft.AspNetCore.Routing.EndpointMiddleware:Information: Executed endpoint '405 HTTP Method Not Supported'
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
    Request finished in 9.3884ms 405 
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 9.3884ms 405 
4个回答

首先要检查此错误消息是否不是 Web api 错误的结果。

为此,请在特殊模式下运行 chrome (windows)

"c:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --user-data-dir="C:/Chrome dev session" --disable-web-security

如果您仍然收到错误,那么我怀疑这可能是由于您的 web api 中的其他错误造成的。您是否检查了 api 控制台是否有任何异常?

干杯

如果您使用的是完整的 IIS 并且遇到问题,请确保排除:

IIS > App or Directory \ HTTP Response Headers \ Access-Control-Allow-Origin

已经定好了。我遇到了一个问题,它出于某种原因已经设置并且覆盖了应用程序的配置。

尝试 Response.Headers.Add("Access-Control-Allow-Origin", " http://IPorDomain:Port "); 它适用于 .Net Core Web API。就我而言,我正在从 angular 使用 Web api。

var itemsOnPage = await _context.Employees
            .OrderBy(e => e.EmpFirstName)               
            .Skip(count * pageIndex)
            .Take(count)
            .ToListAsync();

/*This*/
Response.Headers.Add("Access-Control-Allow-Origin", "http://localhost:4200");
/*This*/
return Ok(itemsOnPage);

首先我要感谢所有试图帮助我的人。我已经解决了这个问题。

首先,我使用Add and Remove Programs卸载了IIS 而且我还关闭了Windows 功能中IIS功能

它需要重新启动PC。之后,这个问题就不会发生了。