简体   繁体   English

在 ASP.NET Core 中允许 Cors Origin

[英]Allow Cors Origin in ASP.NET Core

I am using Microsoft.ApsNetCore.Cors 2.2我正在使用 Microsoft.ApsNetCore.Cors 2.2

"Access to XMLHttpRequest at 'exampleapi.local' from origin 'example.local' has been blocked by CORS policy: “从源 'example.local' 访问 'exampleapi.local' 的 XMLHttpRequest 已被 CORS 策略阻止:
No 'Access-Control-Allow-Origin' header is present on the requested resource."请求的资源上不存在‘Access-Control-Allow-Origin’标头。”

I set the settings with this:我用这个设置设置:

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
    {
        options.AddPolicy("AllowSpecificOrigin",
                builder =>
                {
                    builder                            
                    .AllowAnyOrigin()
                    .AllowAnyMethod()
                    .AllowAnyHeader();
                });
    });

    services.Configure<TokenSettings>(this.Configuration.GetSection("Tokens"));
    services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(opt =>
        {
            opt.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidateAudience = true,
                ValidateLifetime = true,
                ValidateIssuerSigningKey = true,
                ValidIssuer = Configuration["Tokens:Issuer"],
                ValidAudience = Configuration["Tokens:Audience"],
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Configuration["Tokens:SecurityKey"]))
            };
        });

    services.AddMvc();
    services.Configure<LdapConfig>(Configuration.GetSection("ldap"));
    services.AddScoped<ILdapAuthenticationService, LdapAuthenticationService>();
    services.AddScoped<IUserService, UserService>();
    services.AddScoped<IProjectService, ProjectService>();
    services.AddScoped<IProjectMembersService, ProjectMembersService>();
    services.AddScoped<IJourneyUsersService, JourneyUsersService>();
    services.AddScoped<IProjectRolesService, ProjectRolesService>();
    services.AddScoped<IPmoGuardianService, PmoGuardianService>();
    services.AddScoped<IHolidaysService, HolidaysService>();
    services.AddScoped<IMailService, MailService>();
    services.AddScoped<INotificationsService, NotificationsService>();
    services.AddScoped<INotificationUsersService, NotificationUsersService>();
    services.Configure<AWSConfigSes>(Configuration.GetSection("AWSSmtp"));
    services.AddDbContext<JourneyContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("JourneyConnection")));
    services.AddDbContext<TSMContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("TSMConnection")));
    services.AddDbContext<PmoGuardianContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("PmoGuardianConnection")));

}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, IMailService mail, INotificationsService not)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    Recurrence recurrency = Recurrence.GetInstance(not);
    //new TSMClockService(mail);

    app.UseCors("AllowSpecificOrigin");
    app.UseAuthentication();

    app.UseMvc();
}

[Produces("application/json")]
[Route("api/Mail")]
[EnableCors("AllowSpecificOrigin")]

But It doesn't work, always I got the same error但它不起作用,我总是遇到同样的错误

Amy's right in her comment.艾米的评论是对的。 CORS headers need to be set by the target server, not yours. CORS 标头需要由目标服务器设置,而不是您的。

You will often find issues with CORS if you are trying to hook into an API on a different port but running locally on the same IP address (a most common example is localhost:<> trying to ping localhost<>, etc.).如果您尝试挂接到不同端口上的 API 但在同一 IP 地址上本地运行(最常见的示例是 localhost:<> 尝试 ping localhost<> 等),您会经常发现 CORS 问题。

If you are trying to run this on your local machine with Google chrome you can download the below extension which will allow you to toggle on and off the CORS rule so you can test locally: Allow CORS: Access-Control-Allow-Origin如果您尝试使用 Google chrome 在本地计算机上运行此程序,您可以下载以下扩展程序,它允许您打开和关闭 CORS 规则,以便您可以在本地进行测试: 允许 CORS:访问控制允许源

I've just lost a couple of minutes trying to figure out why CORS isn't working for requests from http://localhost:8080 that I've setup according to the official documentation.我刚刚失去了几分钟试图找出为什么CORS不从请求工作的http://本地主机:8080 ,根据官方文档我设置。

Well it's because I added a '/' at the end of the URL.那是因为我在 URL 的末尾添加了一个“/”。 So, remove your '/' from the allowed origins.因此,从允许的来源中删除您的“/”。

There's even a Note on the Microsoft docs about this! Microsoft 文档上甚至有关于此的注释!

Note: The URL must not contain a trailing slash (/).注意:URL 不得包含尾部斜杠 (/)。 If the URL terminates with /, the comparison returns false and no header is returned.如果 URL 以 / 结尾,则比较返回 false 并且不返回标头。

This is the exmple provided here: ASP.NET Core 2.2这是此处提供的示例: ASP.NET Core 2.2

public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(options =>
        {
            options.AddPolicy("AllowSpecificOrigin",
                builder => builder.WithOrigins("http://example.com"));
        });
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, 
        ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        // Shows UseCors with named policy.
        app.UseCors("AllowSpecificOrigin");

        app.Run(async (context) =>
        {
            await context.Response.WriteAsync("Hello World!");
        });
    }

The finally use it like this on the controller or action:最后在控制器或动作上像这样使用它:

[EnableCors("AllowSpecificOrigin")]

Also for some reason make sure that app.UseCors is called before app.UseMVC.同样出于某种原因,请确保在 app.UseMVC 之前调用 app.UseCors。

Also if all you need is CORS from a single origin;此外,如果您只需要来自单一来源的 CORS; you use simpler solution with no policies:您使用没有政策的更简单的解决方案:

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    app.UseCors(
        options => options.WithOrigins("http://example.com").AllowAnyMethod()
    );

    app.UseMvc();
}

I know this is an old question but if like me you're using the appsettings.json file for configuration, be sure to add this:我知道这是一个老问题,但如果像我一样使用appsettings.json文件进行配置,请务必添加以下内容:

"cors": {
  "rules": [
    {
      "origin": "https://localhost:44379",
      "allow": true
    }
  ]
}

This simple addition made everything magically work for me.这个简单的添加使一切对我来说都神奇地工作。

Simple and easy way to do it.简单易行的方法。

  1. Install package安装包

Install-Package Microsoft.AspNetCore.Cors

  1. Put the code below in startup.cs file将下面的代码放在startup.cs文件中

app.UseCors(options => options.AllowAnyOrigin());

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

相关问题 ASP.NET Core CORS WebAPI:没有 Access-Control-Allow-Origin 标头 - ASP.NET Core CORS WebAPI: no Access-Control-Allow-Origin header CORS asp.net 核心 webapi - 缺少 Access-Control-Allow-Origin 标头 - CORS asp.net core webapi - missing Access-Control-Allow-Origin header ASP.NET Core CORS WebAPI:不保留 Access-Control-Allow-Origin 标头 - ASP.NET Core CORS WebAPI: persist no Access-Control-Allow-Origin header CORS 使用 ASP.NET 核心 3.1 的起源问题 - CORS Origin issue using ASP.NET Core 3.1 asp.net Core MVC 2-配置CORS以接受NULL来源 - asp.net Core MVC 2 - configure CORS to accept NULL origin ASP.NET Core Web Api发送Access-Control-Allow-Origin:null CORS头和chrome是错误的,如何修复? - ASP.NET Core Web Api sending Access-Control-Allow-Origin: null CORS header and chrome is erroring, how to fix? Asp.Net Core允许CORS中的IP范围 - Asp.Net Core allow IP ranges in CORS ASP.NET Core 6 中的“访问控制允许来源” - 'Access-Control-Allow-Origin' in ASP.NET Core 6 ASP .NET 核心中 CORS 中的问题 - 响应中的“访问控制允许来源”header 的值不能是通配符 '* - Issue in CORS in ASP .NET Core - The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '* 带有 SignalR 的 ASP.Net MVC 中的 CORS 导致“Access-Control-Allow-Origin”错误 - CORS in ASP.Net MVC with SignalR causes “Access-Control-Allow-Origin” error
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM