C# NET内核中的CORS

C# NET内核中的CORS,c#,web,cors,.net-core,C#,Web,Cors,.net Core,我正试图通过以下方式在.NET Core中启用CORS: public IConfigurationRoot Configuration { get; } public void ConfigureServices(IServiceCollection services) { services.AddCors(options => options.AddPolicy("AllowAll", p => p.AllowAnyOrigin()

我正试图通过以下方式在.NET Core中启用CORS:

    public IConfigurationRoot Configuration { get; }

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

    public void Configure(IApplicationBuilder app)
    {
        app.UseCors("AllowAll");

        app.UseMvc(routes =>
         {
             routes.MapRoute(
                 name: "default",
                 template: "{controller=Home}/{action=Index}/{id?}");
         });

    }
}
然而,当我用Angular 2向我的应用程序发送请求时,我得到了著名的

“请求的服务器上不存在“访问控制允许来源”标头 资源。”

错误消息

我还使用Windows身份验证+WebListener。 如果我与邮递员核实,则唯一的响应标题为:

内容长度→3533 内容类型→应用程序/json; 字符集=utf-8 日期→2016年10月14日星期五12:17:57 GMT服务器→微软HTTPAPI/2.0

所以肯定还是有什么不对劲。有什么建议吗

如果我删除了注释外的行,它可以工作,但我需要Windows身份验证:-(

var host=new WebHostBuilder()
.UseWebListener()
.UseContentRoot(目录.GetCurrentDirectory())
.Useii整合()
.UseStartup()
//.UseWebListener(选项=>options.Listener.AuthenticationManager.AuthenticationSchemes=AuthenticationSchemes.NTLM)
.Build();

假设你有答案,但为了搜索者的利益,我在上的标准教程中也遇到了同样的问题

遇到的众多错误之一:

XMLHttpRequest无法加载localhost:64633/api/blogs.Response 飞行前请求未通过访问控制检查:否 “Access Control Allow Origin”标头出现在请求的服务器上 因此,不允许源“localhost:56573” 访问。响应的HTTP状态代码为500

在玩过之后,下面的代码起作用了。下面发布了完整的类,以帮助理解什么去了哪里

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Cors.Infrastructure;

namespace NetCoreWebApiTesting
{
    public class Startup
    {
        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

            if (env.IsEnvironment("Development"))
            {
                // This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.
                builder.AddApplicationInsightsSettings(developerMode: true);
            }

            builder.AddEnvironmentVariables();
            Configuration = builder.Build();
        }

        public IConfigurationRoot Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container
        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddApplicationInsightsTelemetry(Configuration);

            services.AddMvc().AddJsonOptions(options => options.SerializerSettings.ReferenceLoopHandling =
                                                            Newtonsoft.Json.ReferenceLoopHandling.Ignore);

            // ********************
            // Setup CORS
            // ********************
            var corsBuilder = new CorsPolicyBuilder();
            corsBuilder.AllowAnyHeader();
            corsBuilder.AllowAnyMethod();
            corsBuilder.AllowAnyOrigin(); // For anyone access.
            //corsBuilder.WithOrigins("http://localhost:56573"); // for a specific url. Don't add a forward slash on the end!
            corsBuilder.AllowCredentials();

            services.AddCors(options =>
            {
                options.AddPolicy("SiteCorsPolicy", corsBuilder.Build());
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            app.UseApplicationInsightsRequestTelemetry();

            app.UseApplicationInsightsExceptionTelemetry();

            app.UseMvc();

            // ********************
            // USE CORS - might not be required.
            // ********************
            app.UseCors("SiteCorsPolicy");
        }
    }
}
要使用它,您可以在控制器或方法上添加
EnableCorsAttribute

[EnableCors("SiteCorsPolicy")]
[Route("api/[controller]")]
public class BlogsController : Controller
{

}

当我使用下面的代码调用它时(使用标准js/jQuery以便复制和粘贴),通信停止被拒绝

function HandleClick() {

    var entityData = {
        "blogId": 2,
        "url": "http://blog.com/blog1",
        "posts": [
        {
            "postId": 3,
            "title": "Post 1-1",
            "content": "This is post 1 for blog 1",
            "blogId": 2
        },
        {
            "postId": 4,
            "title": "Post 1-2",
            "content": "This is post 2 for blog 1",
            "blogId": 2
        }
        ]
    };

    $.ajax({
        type: "POST",
        url: "http://localhost:64633/api/blogs",
        async: true,
        cache: false,
        crossDomain: true,
        data: JSON.stringify(entityData),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (responseData, textStatus, jqXHR) {
            var value = responseData;
        },
        error: function (responseData, textStatus, errorThrown) {
            alert('POST failed.');
        }
    });
}

这种方法可以正常工作,只需在angular2和.net内核上试用。 OP面临的问题是,这不适用于windows身份验证。我假设windows身份验证中间件发生在请求通过之前,在这种情况下,它会中断。最好的办法是在cors中间件在配置中处理之后,看看是否有办法启用windows身份验证中间件

那么命令就是

App.UseCors()

App.UseWindowsAuth()

App.UseMVC()

它们必须按此顺序发生,才能起作用

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

    public void Configure(IApplicationBuilder app)
    {
        app.UseCors("AllowAll");

        app.UseMvc(routes =>
         {
             routes.MapRoute(
                 name: "default",
                 template: "{controller=Home}/{action=Index}/{id?}");
         });

    }

@HockeyJ的答案是正确的,但如果需要,您可以做一些更简洁的事情

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();

    //Or if you want to chose what to include
    services.AddMvcCore()
            .AddCors()
            (...)
}


public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    //Cors
    app.UseCors(builder =>
    {
        builder.AllowAnyHeader();
        builder.AllowAnyMethod();
        builder.AllowCredentials();
        builder.AllowAnyOrigin(); // For anyone access.
        //corsBuilder.WithOrigins("http://localhost:56573"); // for a specific url.
     });
}

文档遗漏的是.AllowAnyMethod()的重要性。如果不存在,可怕的“不允许访问控制允许源代码”将一直困扰您。在您的代码中,它就在那里,所以我猜您遗漏了在jour客户端应用程序中设置正确的头

我个人通过允许以下所有方式使其发挥作用:

app.UseCors(b => b.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin().AllowCredentials());
我的角度后处理函数如下:

post(model) {

    let headers = new Headers({
      'Content-Type':'application/json; charset=utf-8;' 
      ,'Accept':'*/*'
    });


    let options = new RequestOptions({ headers: headers });
    let body = JSON.stringify(model);

    return this.http.post(
      'http://localhost:58847/api/TestPost', body, options)
      .map((response: Response) => {
        let res = response.json();
        return res;
      }
    );
}

在那之后,您可以通过指定来源等方式逐步提升。在ASPNET CORE 2.0中,以下内容适用于我

   public void ConfigureServices(IServiceCollection services)
    {

        services.Configure<MvcOptions>(options =>
        {
            options.Filters.Add(new CorsAuthorizationFilterFactory("AllowSpecificOrigin"));
        });
        services.AddCors(options =>
        {
            options.AddPolicy("AllowSpecificOrigin",
                builder => builder.WithOrigins("http://localhost:5000").AllowAnyHeader()
                .AllowAnyMethod());
        });

        services.AddMvc()
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {

        loggerFactory.AddConsole();
        loggerFactory.AddDebug(LogLevel.Information);

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

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

        app.UseStaticFiles();
        app.UseAuthentication();


        app.UseMvcWithDefaultRoute();
    }
}
public void配置服务(IServiceCollection服务)
{
配置(选项=>
{
options.Filters.Add(新的CorsAuthorizationFilterFactory(“AllowSpecificationCorigin”);
});
services.AddCors(选项=>
{
options.AddPolicy(“AllowSpecificCorigin”,
builder=>builder.WithOrigins(“http://localhost:5000)。AllowAnyHeader()
.AllowAnyMethod());
});
services.AddMvc()
}
//此方法由运行时调用。请使用此方法配置HTTP请求管道。
公共无效配置(IApplicationBuilder应用程序,IHostingEnvironment环境)
{
loggerFactory.AddConsole();
loggerFactory.AddDebug(LogLevel.Information);
if(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
//显示具有命名策略的UseCors。
应用程序UseCors(“AllowSpecificCorigin”);
app.UseStaticFiles();
app.UseAuthentication();
app.UseMvcWithDefaultRoute();
}
}

您只需要在StartUp类的ConfigureService方法中添加这个

services.AddCors ();
这在Startup类的Configure方法中,然后就可以正常工作了

app.UseCors (builder => builder
                 .AllowAnyOrigin ()
                 .AllowAnyHeader ()
                 .AllowAnyMethod ());

在.Net Core中启用CORS没有更多需要添加的内容

我在应用程序中遇到了CORS问题。我觉得我正确地实现了逻辑,但仍然出现访问控制允许源403错误。我尝试了上面提到的所有设置,但没有任何效果

后来我发现我的问题与CORS无关,我实现了一个自定义属性

[Route("v1/[Controller]")]
[ServiceFilter(typeof(MyCustomFilterAttribute))]
public class MySpecialListsController 
对控制器的调用正确地使其进入了OnActionExecuting方法

public override void OnActionExecuting(ActionExecutingContext context)

筛选器中的逻辑引发异常,并显示为CORS 403错误。

appsettings.json中添加此部分

"App": {
  "CorsOrigins": "http://yourdomain"
}


注意:
appsettings中的
App:CorsOrigins

尝试在“配置”方法中添加cors策略


我刚刚修复了Core 3.1中Cors的问题。我几乎遵循了所有的示例和文档。不幸的是,直到我在AddPolicy部分中为构建器创建了.Build()之后,才开始工作

        services.AddCors(options => {
            options.AddPolicy(
                name: OrginPolicyKey, 
                builder => builder.WithOrigins("http://localhost:3000")
                    .AllowAnyHeader()
                    .AllowAnyMethod()
                    .Build() // <--- This right here
            );
        });
services.AddCors(选项=>{
options.AddPolicy(
名称:OrginPolicyKey,
builder=>builder.WithOrigins(“http://localhost:3000")
.AllowAnyHeader()
.AllowAnyMethod()

.Build()//我也遇到了同样的问题,但使用JWT。将顺序更改为:app.UseCors()app.useJWTBeareAuthentication()app.UseMvc()解决了它,谢谢!我也遇到了同样的问题,但似乎无法解决@user1527312My good这为我解决了它!谢谢!这
"App": {
  "CorsOrigins": "http://yourdomain"
}
services.AddCors(options => {
  options.AddPolicy(DefaultCorsPolicyName, builder => {

   builder.WithOrigins(
     _appConfiguration["App:CorsOrigins"]
       .Split(",", StringSplitOptions.RemoveEmptyEntries)
       .Select(o => o.RemovePostFix("/"))
       .ToArray()
   ).SetIsOriginAllowedToAllowWildcardSubdomains()
    .AllowAnyHeader()
    .AllowAnyMethod()
    .AllowCredentials();
  });
});
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        app.UseRouting();
        app.UseCors(option =>
            option.AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader()
                );
    }
        services.AddCors(options => {
            options.AddPolicy(
                name: OrginPolicyKey, 
                builder => builder.WithOrigins("http://localhost:3000")
                    .AllowAnyHeader()
                    .AllowAnyMethod()
                    .Build() // <--- This right here
            );
        });
        app.UseCors(OrginPolicyKey); // <--- First

        // Then routing stuff..
        app.UseRouting();
        app.UseEndpoints(endpoints =>
        {
            endpoints
                .MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}"
                );
        });