如何使用.NET Core 2配置Angular 6以允许来自任何主机的CORS? [英] How to Configure Angular 6 with .NET Core 2 to allow CORS from any host?

查看:75
本文介绍了如何使用.NET Core 2配置Angular 6以允许来自任何主机的CORS?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的Angular App,它在4200本地运行,我正在测试使用.net core在5000本地运行的Web API.我的startup.cs的CORS配置正确,允许我相信的所有内容.

I have a simple Angular App running locally on 4200 i am testing with a web api running locally on 5000 using .net core. My startup.cs has CORS configured correctly to allow everything i believe.

在ConfigureServices部分中,我有: services.AddCors();

In the ConfigureServices section i have: services.AddCors();

在配置"部分中,我有:

In the Configure section i have:

app.UseCors(options => options.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin());

但是,当我尝试打我的webapi时,仍然可以在浏览器中找到它.

However when i try and hit my webapi i still get this in the browser.

来自来源" http://localhost:4200 "已被CORS策略阻止:对预检请求的响应没有" t通过访问控制检查:飞行前请求不允许重定向.

from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.

我查看了其他答案,它们似乎都具有我尝试没有改变的这种或类似变化.不确定我还需要做什么?

I have looked at the other answers and they all seem to have this or similar variations that i have tried with no change. Not sure what else i need to do?

推荐答案

在ConfigureConfigs方法中添加以下代码段.编辑此选项以仅允许自定义标题.

Add the following code snippet in the method ConfigureServices. Edit this for allowing only custom headers.

// Add service and create Policy with options
        services.AddCors(options =>
        {
            options.AddPolicy("CorsPolicy",
                builder => builder.AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials()
                );
        });

在Configure方法中添加以下内容

Add the following in Configure method

app.UseCors("CorsPolicy");

向控制器添加"EnableCors"属性.

Add 'EnableCors' attribute to the controller.

[EnableCors("CorsPolicy")]

这篇关于如何使用.NET Core 2配置Angular 6以允许来自任何主机的CORS?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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