Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.0k views
in Technique[技术] by (71.8m points)

angular - asp net core - No 'Access-Control-Allow-Origin' header is present on the requested resource

I have set two net core apps (netcoreapp2.0).

One is a net core webapi (backend app) that is responsible for returning data to the user. This app is running on http://localhost:5001

The other is a net core webapp(front end app) loading angular in index.cshtml. This app is running on http://localhost:5000

The problem i have is that after setting [Authorize] to my controllers in the api i get the No 'Access-Control-Allow-Origin' header is present on the requested resource error

This is contained in the startup of the web api project:

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

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

    }

Controller classes have: [EnableCors("AllowAll")] where AllowAll is the name of the policy i set in startup above

Here is also the code in angular that returns the headers set in the requests:

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;
    }
}

The preflight request is successful:

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

The actual request after that fails:

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

This is the message in the console:

XMLHttpRequest cannot load http://localhost:5001/api/Resource/data/el/Building. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:5000' is therefore not allowed access. The response had HTTP status code 500.

Any ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is probably because an error occurred in the web API. Hence the 500 HTTP status code. The Access-Control-Allow-Origin is not present on the response because the error handling in ASP.NET Core clears the response headers, which results in an error in the browser.

Try to turn on exceptions/logging and diagnose what's causing the error in your web API.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...