angular - asp net core - 请求的资源上不存在 'Access-Control-Allow-Origin' header

标签 angular asp.net-core oauth-2.0

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

一个是net core webapi(后端app),负责向用户返回数据。此应用程序在 http://localhost:5001 上运行

另一个是在index.cshtml中加载angular的net core webapp(front end app)。此应用程序在 http://localhost:5000 上运行

我遇到的问题是,在 api 中为我的 Controller 设置 [Authorize] 后,我得到了 No 'Access-Control-Allow-Origin' header is present on the requested resource 错误

这个包含在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?}");
        });

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

    }

Controller 类有: [EnableCors("AllowAll")] 其中 AllowAll 是我在上面启动时设置的策略的名称

这也是返回请求中设置的 header 的 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 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.

有什么想法吗?

最佳答案

这可能是因为网络 API 发生了错误。因此 500 HTTP 状态代码。 Access-Control-Allow-Origin 未出现在响应中,因为 ASP.NET Core 中的错误处理会清除响应 header ,这会导致浏览器出错。

尝试打开异常/日志记录并诊断导致 Web API 错误的原因。

关于angular - asp net core - 请求的资源上不存在 'Access-Control-Allow-Origin' header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46297242/

相关文章:

ios - ionic 2-手指离开屏幕时不会触发滚动事件

angular - 无法读取未定义的 CRUD 操作的类型 '_id ' 的属性

asp.net-core - .NET Core Azure servicebusqueue 消息数

ios - 使用 Swift p2/OAuth2 并行刷新 OAuth2 访问 token 请求

ruby-on-rails - 如何同时使用设计和门卫 gem ?

android - NativeScript 模式在 ios 上全屏显示

angular - 指定值无法解析,或使用数字管道时超出范围

asp.net-core - 重定向到 Blazor Server Azure B2C 身份验证中的登录

asp.net-core - 找不到类型或命名空间名称 'IWebHostEnvironment'(是否缺少 using 指令或程序集引用?)

JavaEE + Socialauth库,登录后存储什么