请求的资源上存在“ Access-Control-Allow-Origin”标头

时间:2020-03-30 04:59:02

标签: angular .net-core cors asp.net-core-webapi

我正在尝试从角度应用程序连接到我的.net核心API。当我尝试这样做时,我收到一条错误消息:

Access to XMLHttpRequest at 'https://localhost:44378/api/recloadprime' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

下面是我的角度应用程序发出的控制台消息:

enter image description here

这是我要解决的错误。我在startup.cs文件的ConfigureServices方法中添加了services.addCors:

public void ConfigureServices(IServiceCollection services)
    {

        services.AddCors(options =>
        {
            options.AddPolicy("AllowAnyCorsPolicy", policy => policy.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin());
        });

        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
            services.AddControllers();
           services.AddDbContext<db_recloadContext>();

    }

在configure方法中,我输入了以下代码:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();

            }
            else
            {
                app.UseHsts();
            }
           app.UseCors("AllowAnyCorsPolicy");
           app.UseHttpsRedirection();
           app.UseRouting();
           app.UseAuthorization();
           app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }

在我的控制器中,我有以下代码:

namespace RecLoad.Controllers
{
    [Route("api/[controller]")]
    [EnableCors("AllowAnyCorsPolicy")]
    public class RecLoadPrimeController : ControllerBase
    {
        private readonly db_recloadContext _context;

        public RecLoadPrimeController(db_recloadContext context)
        {

            _context = context;
        }

我遵循Microsoft文档中的说明以及stackoverflow帖子之一:

https://stackoverflow.com/questions/42199757/enable-options-header-for-cors-on-net-core-web-api

和Microsoft文章:

https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1

我花了很多时间浏览其他文档,并在startup.cs文件中尝试了不同的代码,但是这种错误并没有消失。

下面是运行良好的我的api:

[HttpGet]
       public ActionResult<string> Get()
        {

            return "This is a test";

        }

下面是我的开发人员工具的标题:

enter image description here

我也在Chrome浏览器中启用了CORS扩展程序。下面是图像:

enter image description here

我们将不胜感激任何帮助。

1 个答案:

答案 0 :(得分:2)

要使其正常运行,您可以尝试以下操作:

1)在ConfigureServices方法中,调用AddCors以将CORS服务配置为最初允许任何来源:

services.AddCors(options => 
{
    options.AddPolicy("AllowAnyCorsPolicy", policy => policy.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin());
});

2)在Configure方法中添加UseCors,这将中间件添加到Web应用程序管道:

app.UseRouting();
app.UseCors("AllowAnyCorsPolicy");
app.UseMvc();

https://github.com/dotnet/aspnetcore/issues/17830中所述,由于ASP.NET Core 3.1 .UseCors()必须在.UseRouting()之后调用。

此初始配置正常工作时,可以在以后根据您的要求进行修改。