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

时间:2018-11-27 19:46:33

标签: javascript c# .net reactjs cors

这将显示在我的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 个答案:

答案 0 :(得分:1)

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

为此,请以特殊模式运行Chrome(Windows)

“ c:\ Program Files(x86)\ Google \ Chrome \ Application \ chrome.exe“ --user-data-dir =” C:/ Chrome开发者会话“ --disable-web-security

如果您仍然收到错误,则我怀疑这可能是由于您的Web API中的其他错误所致。您是否检查了api控制台中的任何异常?

欢呼

答案 1 :(得分:0)

尝试Response.Headers.Add(“ Access-Control-Allow-Origin”,“ http://IPorDomain:Port”);它适用于.Net Core Web API。就我而言,我是从角度上使用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);

答案 2 :(得分:0)

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

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

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

答案 3 :(得分:0)

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

首先,我使用添加和删除程序卸载了 IIS
而且我还关闭了 Windows功能中的 IIS 功能。

需要重新启动PC。 之后,该问题就不会发生。

相关问题