.NET Core 2.0-仍然看不到“ Access-Control-Allow-Origin”标头错误

Ste*_*ace 5 .net c# asp.net asp.net-web-api asp.net-core

我在这方面机智。我已经研究过类似问题的其他答案,因此没有任何运气。

我相当确定我已经正确启用了CORS,以允许来自所有来源的传入请求(在这种情况下为POST请求),但是我看到以下错误:

无法加载http:// localhost:5000 / expenses:所请求的资源上没有“ Access-Control-Allow-Origin”标头。因此,不允许访问源' http:// localhost:4200 '。响应的HTTP状态码为500。

这是我在webAPI项目中启用CORS的方式:

Startup.cs中的相关方法

 // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors();
            services.AddMvc();

            services.AddDbContext<ExpensesDbContext>(options =>
                                                    options.UseMySQL(Configuration.GetConnectionString("DefaultConnection")));
            services.AddTransient<IBaseDa<Accounts>, AccountsDataAccess>();
            services.AddTransient<IExpensesDa, ExpensesDa>();
        }

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

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

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

            app.UseMvc();
        }
Run Code Online (Sandbox Code Playgroud)

如果我使用.AllowAnyOrigin().AllowAnyMethod(),为什么会看到上述错误?

Ale*_*sko 9

在这种情况下我挠了一阵子。我正确启用了 CORS,但有些调用仍然返回 Access-Control-Allow-Origin 错误。我发现了问题……鬼鬼祟祟的鬼鬼祟祟的问题……

我们的问题是由我们如何使用app.UseExceptionHandler. 具体来说,这是我们使用的代码,除了我们的原始代码没有该context.Response.Headers.Add("Access-Control-Allow-Origin", "*");行。

app.UseExceptionHandler(errorApp =>
{
    errorApp.Run(async context =>
    {
        var errorFeature = context.Features.Get<IExceptionHandlerFeature>();
        var exception = errorFeature.Error;

        var problemDetails = new ProblemDetails
        {
            Title = R.ErrorUnexpected,
            Status = status,
            Detail =
              $"{exception.Message} {exception.InnerException?.Message}"
        };

        context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
        context.Response.StatusCode = problemDetails.Status.GetValueOrDefault();
        context.Response.WriteJson(problemDetails, "application/problem+json");

        await Task.CompletedTask;
    });
});
Run Code Online (Sandbox Code Playgroud)

app.UseExceptionHandler是一个比控制器动作低得多的功能,因此不参与任何与 CORS 相关的本机操作。添加context.Response.Headers.Add("Access-Control-Allow-Origin", "*");修复了问题。


小智 3

netCore2.0 ( http://localhost:5000/ ) + Angular ( http://localhost:4200的组合 ) + chrome = Access-Control-Allow-Origin我以前遇到过这个问题,我花了 3 天才意识到 chrome 总是会抛出这个错误。我认为这是因为 chrome 将 localhost 视为来源,而忽略端口,即使中间件明确告诉它不要太特别,尤其是在 POST 请求上。

我会尝试在您的startup.cs配置服务中定义一个策略:

  public void ConfigureServices(IServiceCollection services)
        {
  //add cors service
            services.AddCors(options => options.AddPolicy("Cors",
                builder =>
                {
                    builder.AllowAnyOrigin()
                    .AllowAnyMethod()
                    .AllowAnyHeader();
                }));
Run Code Online (Sandbox Code Playgroud)

然后在您的配置方法中我会添加:

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

            //authentication added 
            app.UseAuthentication();

            app.UseCors("Cors");
            app.UseMvc();
        }
Run Code Online (Sandbox Code Playgroud)

...这很可能行不通,但任何人都可以尝试...这让我发疯,我需要满足地看到请求是否甚至尝试访问 asp.netCore 后端:我使用

如果您确实想查看,我会清除您的缓存和 cookie,然后添加 IHttpContextAccessor 以对请求中发生的情况进行低级别控制。在遇到同样问题的困境中,我需要角度来发送图像。我收到了 annyoing Origin 错误,然后通过实验,我通过将 IHttpContextAccessor 注入到我的控制器中获得了图像,并且

调试

public void ConfigureServices(IServiceCollection services)
{
  //add cors service
                services.AddCors(options => options.AddPolicy("Cors",
                    builder =>
                    {
                        builder.AllowAnyOrigin()
                        .AllowAnyMethod()
                        .AllowAnyHeader();
                    }));

    services.AddMvc();

         // register an IHttpContextAccessor so we can access the current
            // HttpContext in services by injecting it
            //---we use to this pull out the contents of the request

    services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
}
Run Code Online (Sandbox Code Playgroud)

你想将它注入到你所在的任何控制器中

用于检索 POST 请求的 json 对象。我将使用该示例作为家庭控制器:

public class HomeController : Controller
    {

        // make a read only field
        private readonly IHttpContextAccessor _httpContextAccessor;

    //create ctor for controller and inject it
    public UserService(IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
    }

    // now in your post method use this to see what the if anything came in through the request:
    public async Task<IActionResult> Picload(IFormFile file){//---always null

    // in my problem I was loading and image from.
    var file =  _httpContextAccessor.HttpContext.Request.Form.Files[0];
}
Run Code Online (Sandbox Code Playgroud)

使用这个它可以让我访问图像chrome给我一个起源错误。