.NET Core中的CORS

Dav*_*vid 40 c# cors web .net-core

我试图以这种方式在.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?}");
         });

    }
}
Run Code Online (Sandbox Code Playgroud)

但是,当我向Angular 2发送请求到我的应用程序时,我得到了名人

"请求的资源上没有'Access-Control-Allow-Origin'标头."

错误信息.

我也使用Windows身份验证+ WebListener.如果我与邮递员核对,唯一的响应标题是:

Content-Length→3533 Content-Type→application/json; charset = utf-8日期→星期五,2016年10月14日12:17:57 GMT服务器→Microsoft-HTTPAPI/2.0

所以必须仍然配置错误.有什么建议?

如果我删除了outcommented行它,但我需要Windows身份验证:-(

        var host = new WebHostBuilder()
            .UseWebListener()
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseIISIntegration()
            .UseStartup<Startup>()
            //.UseWebListener(options => options.Listener.AuthenticationManager.AuthenticationSchemes = AuthenticationSchemes.NTLM)
            .Build();
Run Code Online (Sandbox Code Playgroud)

Hoc*_*eyJ 44

假设您有答案,但为了搜索者的利益,我在.NET Core Cors的标准教程中遇到了同样的问题.

遇到的许多错误之一:

XMLHttpRequest无法加载localhost:64633/api/blogs.对预检请求的响应未通过访问控制检查:请求的资源上不存在"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");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

要使用它,您可以EnableCorsAttribute在控制器或方法上添加.例如

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

}
Run Code Online (Sandbox Code Playgroud)

要么

// POST api/value
[EnableCors("SiteCorsPolicy")]
[HttpPost]
public HttpResponseMessage Post([FromBody]Blog value)
{
    // Do something with the blog here....

    var msg = new HttpResponseMessage(System.Net.HttpStatusCode.OK);
    return msg;

}
Run Code Online (Sandbox Code Playgroud)

当我使用以下代码调用它时(使用标准的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.');
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

  • `//用于特定的网址。别在结尾加上正斜杠。。。老兄。。。 (2认同)

小智 26

这种方式正常工作,只是在带有.net核心的angular2上尝试过.OP所面临的问题是,这不适用于Windows身份验证.我假设Windows身份验证的中间件正在发出请求之前发生,在这种情况下它会破坏.最好的办法是看看在配置中处理cors中间件后是否有办法启用Windows auth中间件.

那顺序就是

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?}");
         });

    }
Run Code Online (Sandbox Code Playgroud)

  • 我有同样的问题,但有JWT.将订单更改为:app.UseCors()app.UseJwtBearerAuthentication()app.UseMvc()解决了它,谢谢! (2认同)

小智 14

在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();
    }
}
Run Code Online (Sandbox Code Playgroud)

  • Auth过滤器工厂可以解决这个问题。谢谢! (2认同)

Ste*_*oot 13

文档遗漏的是.AllowAnyMethod()的重要性.如果不存在,可怕的No'Access-Control-Allow-Origin'会让你烦恼.在你的代码中它就在那里,所以我猜你错过了在jour客户端应用程序中设置正确的标题.

我个人通过允许所有人来完成工作:

app.UseCors(b => b.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin().AllowCredentials());
Run Code Online (Sandbox Code Playgroud)

而我的Angular帖子的功能如下:

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;
      }
    );
}
Run Code Online (Sandbox Code Playgroud)

之后,您可以通过指定原点等逐步完成工作.

  • `app.UseCors(builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());`为我工作.谢谢Stefan! (2认同)

小智 6

将此部分添加到 appsettings.json

"App": {
  "CorsOrigins": "http://yourdomain"
}
Run Code Online (Sandbox Code Playgroud)

services.AddCors(options => {
  options.AddPolicy(DefaultCorsPolicyName, builder => {

   builder.WithOrigins(
     _appConfiguration["App:CorsOrigins"]
       .Split(",", StringSplitOptions.RemoveEmptyEntries)
       .Select(o => o.RemovePostFix("/"))
       .ToArray()
   ).SetIsOriginAllowedToAllowWildcardSubdomains()
    .AllowAnyHeader()
    .AllowAnyMethod()
    .AllowCredentials();
  });
});
Run Code Online (Sandbox Code Playgroud)

注意:App:CorsOriginsinappsettings.json可以包含多个地址,用逗号分隔。


Ale*_*ert 5

我刚刚修复了 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
            );
        });
Run Code Online (Sandbox Code Playgroud)

另外,其他人提到在其余路由和 UseMvc 内容之前调用 UseCors(OrginPolicyKey) 。这是正确的,我看到在路线部分之后放置 UseCors 破坏了它。下面是我的设置方式。

        app.UseCors(OrginPolicyKey); // <--- First

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

谁知道需要建造一个建筑商;D