无法使CORS适用于ASP.NET Core Web API [英] Can't get CORS working for ASP.NET Core Web API

查看:98
本文介绍了无法使CORS适用于ASP.NET Core Web API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个在本地运行的应用程序。一种是提供JSON响应的ASP.NET Core Web API( http:// localhost:8081 )。另一个是调用该API的Javascript应用程序( http:// localhost:8080 )。我正在测试的API端点是一个POST请求,并且我已与Fiddler确认此端点正在工作。

I have two applications running locally. One is an ASP.NET Core Web API (http://localhost:8081) serving up JSON responses. The other is a Javascript app (http://localhost:8080) making calls to the API. The API endpoint I'm testing with is a POST request and I've confirmed with Fiddler that this endpoint is working.

当我从Javascript应用发出POST请求时在Chrome中,我看到此错误:

When I make the POST request from my Javascript app in Chrome I see this error:


无法加载 http:// localhost:8081 / api / search :对预检
请求的响应未通过访问控制检查:否
'Access-Control-Allow- Origin的标头出现在请求的
资源上。因此,不允许
访问源' http:// localhost:8080

但是,这是我的API 启动的全部内容:

However, this is the full content of my API's Startup:

public Startup(IConfiguration configuration)
{
    Configuration = configuration;
}

public IConfiguration Configuration { get; }

public void ConfigureServices(IServiceCollection services)
{
    services
        .AddMvcCore()
        .AddJsonFormatters()
        .AddCors(options =>
        {
            options.AddPolicy("DefaultCorsPolicy",
                builder => builder
                    .WithOrigins("http://localhost:8080")
                    .AllowAnyMethod());
        });
}

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

    app.UseCors("DefaultCorsPolicy");

    app.UseMvc();
}

我一直遵循 Microsoft文档,所以我不确定我错过了什么。

I've followed the Microsoft docs, so I'm not sure what I've missed.

这是我从Fiddler的端点收到的原始响应:

Here is the raw response I get from this endpoint in Fiddler:

HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Server: Kestrel
X-Powered-By: ASP.NET
Date: Sat, 10 Mar 2018 09:23:46 GMT
Content-Length: 37

[{"id":1,"name":"lorem ipsum dolor"}]

如您所见,没有 Access-Control-Allow-Origin 标头存在。

As you can see, no Access-Control-Allow-Origin header is present.

推荐答案

您可以尝试在services.UseCors()调用中而不是services.AddCors()上直接配置CORS选项。

You can try to configure CORS options right in services.UseCors() call, rather than services.AddCors().

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors();
    services.AddMvcCore();
    ...
}


public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseCors(builder => builder
        .WithOrigins("http://localhost:8000")
        .AllowAnyHeader()
        .AllowAnyMethod()
    );

    app.UseMvcCore();
    ...
}




注意:通过清除客户端缓存(如果有)对其进行测试。在Chrome> F12>网络选项卡>勾选禁用缓存复选框>刷新页面。

这篇关于无法使CORS适用于ASP.NET Core Web API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆