asp net core - No' Access-Control-Allow-Origin'标头出现在请求的资源上

时间:2017-09-19 09:50:13

标签: angular asp.net-core oauth-2.0 cors

我设置了两个网络核心应用程序(netcoreapp2.0)。

一个是网络核心webapi(后端应用程序),负责将数据返回给用户。此应用正在http://localhost:5001

上运行

另一个是在core.cshtml中加载角度的网络核心webapp(前端应用程序)。此应用正在http://localhost:5000

上运行

我遇到的问题是,在api中将[授权]设置到我的控制器后,我得到 No' Access-Control-Allow-Origin'标头出现在请求的资源上错误

这包含在web api项目的启动中:

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

        services.AddCors(options =>
        {
            options.AddPolicy("AllowAll",
                    builder =>
                    {
                        builder.WithOrigins("http://localhost:5000")
                               .AllowAnyMethod()
                               .AllowAnyHeader()
                               .AllowCredentials()
                               .WithExposedHeaders("Authorization", "WWW-Authenticate");
                    });
        });

        services
            .AddMvcCore()
            .AddJsonFormatters()
            .AddAuthorization();

        ..................................
    }

    public void Configure(IApplicationBuilder app)
    {
        ...................................

        app.UseCors("AllowAll");

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

        ...................................           

    }

控制器类有: [EnableCors(" AllowAll&#34)] 其中AllowAll是我在上面启动时设置的策略的名称

以下是angular中的代码,它返回请求中设置的标头:

getAuthHeaders(): Headers {
    if (this.oauthService.hasValidAccessToken) {
        var headers = new Headers();
        headers.set('Accept', '*/*');
        headers.set('Access-Control-Allow-Credentials', 'true');
        headers.set('Authorization', 'Bearer ' + this.oauthService.getAccessToken());
        return headers;
    } else {
        return null;
    }
}

预检请求成功:

Request URL:http://localhost:5001/api/Resource/data/el/Building
Request Method:OPTIONS
Status Code:204 No Content
Remote Address:[::1]:5001
Referrer Policy:no-referrer-when-downgrade
Response Headers
view source
Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:access-control-allow-credentials,authorization
Access-Control-Allow-Origin:http://localhost:5000
Date:Tue, 19 Sep 2017 09:55:27 GMT
Server:Kestrel
X-Powered-By:ASP.NET
X-SourceFiles:=?UTF-8?B?QzpcUHJvamVjdHNcU3VuU29mdFxQTVNcc3Vuc29mdC5wbXNcU3VuU29mdC5QTVMuQVBJXGFwaVxSZXNvdXJjZVxkYXRhXGVsXEJ1aWxkaW5n?=
Request Headers
view source
Accept:*/*
Accept-Encoding:gzip, deflate, br
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:access-control-allow-credentials,authorization
Access-Control-Request-Method:GET
Connection:keep-alive
Host:localhost:5001
Origin:http://localhost:5000
Referer:http://localhost:5000/list/Building
User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36

之后的实际请求失败:

Request URL:http://localhost:5001/api/Resource/data/el/Building
Request Method:GET
Status Code:500 Internal Server Error
Remote Address:[::1]:5001
Referrer Policy:no-referrer-when-downgrade
Response Headers
view source
Content-Length:0
Date:Tue, 19 Sep 2017 09:55:27 GMT
Server:Kestrel
X-Powered-By:ASP.NET
X-SourceFiles:=?UTF-8?B?QzpcUHJvamVjdHNcU3VuU29mdFxQTVNcc3Vuc29mdC5wbXNcU3VuU29mdC5QTVMuQVBJXGFwaVxSZXNvdXJjZVxkYXRhXGVsXEJ1aWxkaW5n?=
Request Headers
view source
Accept:*/*
Accept-Encoding:gzip, deflate, br
Accept-Language:en-US,en;q=0.8
Access-Control-Allow-Credentials:true
Authorization:Bearer eyJhbGciOiJSUzI1NiIsImtpZCI6Ijg0YTI1NDQ0NmEyMWIwYWEwNTk0MjQwYmJiMzJiMmI1IiwidHlwIjoiSldUIn0.eyJuYmYiOjE1MDU4MTMzODIsImV4cCI6MTUwNTgxNjk4MiwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo1NTU1IiwiYXVkIjoiaHR0cDovL2xvY2FsaG9zdDo1NTU1L3Jlc291cmNlcyIsImNsaWVudF9pZCI6IlNVTlNPRlQuUE1TLlNQQSIsInN1YiI6ImViY2JmNDcxLTZjMTgtNDczYS1iOWFkLWEyMzEwNTE5MjM4MyIsImF1dGhfdGltZSI6MTUwNTgxMzM4MiwiaWRwIjoibG9jYWwiLCJzY29wZSI6WyJvcGVuaWQiLCJwcm9maWxlIiwiZW1haWwiXSwiYW1yIjpbInB3ZCJdfQ.F7L06TWGiyXmZ8kZQBW3JDT_qaFyx3eQ_TafMLtpnBjUxPgKxKind_FUlNfGJufN-17HOW4tLVQljsH53z-a1N4JNOJ0YmlrnIGEWq3JGASnnqJPX2VUOjQR63JeRiwzs9LsTCngfSeHMrgAzEnDQRfw2lBU6Z3oN5iAu-1vE9yexLn009Ie-FVBscyZJkklTsMPJCuX6lO18_DGPRxhKlmhV3vVpNal97l0qh1DWdTd1Exb6Jye1svxyxUlonqj5oUT1JMMKpcW-9qvwB62bX8vG5_NaVdoaDu7RhntA9XinbLceIIat4V9O1hL9dYJKziB1MIJJrEynxci89AOLg
Connection:keep-alive
Host:localhost:5001
Origin:http://localhost:5000
Referer:http://localhost:5000/list/Building
User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36

这是控制台中的消息:

  

XMLHttpRequest无法加载   http://localhost:5001/api/Resource/data/el/Building。没有   '访问控制允许来源'标题出现在请求的上   资源。起源' http://localhost:5000'因此是不允许的   访问。响应的HTTP状态代码为500。

有什么想法吗?

1 个答案:

答案 0 :(得分:6)

这可能是因为Web API发生了错误。因此500 HTTP状态代码。响应中不存在Access-Control-Allow-Origin,因为ASP.NET Core中的错误处理会清除响应标头,从而导致浏览器出错。

尝试启用例外/日志记录并诊断导致Web API出错的原因。