net core配置跨域

什么是跨域?
浏览器从一个域名的网页去请求另一个域名的资源时,域名、端口、协议任一不同,都是跨域
跨域的几种情况
 1、端口和协议的不同
 2、localhost和127.0.0.1虽然都指向本机,但也属于跨域

一般情况WebApi都是跨域请求,没有设置跨域一般会报以下错误
关键字 Access-Control-Allow-Origin cors

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:48057' is therefore not allowed access.

ASP.net Core 跨域有两种,全局和区域

1.设置特定来源可以跨域,打开Startup.cs文件 注入IConfiguration 修改ConfigureServices方法

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

        public IConfiguration Configuration { get; }

在ConfigureServices方法中添加

services.AddCors(options =>
            {
                // Policy 名稱 CorsPolicy 是自訂的,可以自己改
                options.AddPolicy("qwer", policy =>
                {
                    // 設定允許跨域的來源,有多個的話可以用 `,` 隔開
                    string CorsUrl= Configuration.GetConnectionString("CorsOrigins");//通过注入的IConfiguration 获取appsetting.json中的自定义路径
                    string[] CoreArray = CorsUrl.Split(',');//appsetting.json中的配置
                    //policy.WithOrigins("http://localhost:8080", "http://192.168.0.86:8080","http://123.123.123.123:5555")//写死的方式   不方便
                    policy.WithOrigins(CoreArray)
                            .AllowAnyHeader()
                            .AllowAnyMethod()
                            .AllowCredentials();
                });
            });

在这里插入图片描述
appsetting.json文件
在这里插入图片描述

修改Configure方法
添加

app.UseCors("qwer");//必须位于UserMvc之前 

在这里插入图片描述

2.允许所有来源 不建议使用

修改ConfigureServices方法

//配置跨域处理,允许所有来源:
            services.AddCors(options =>
            options.AddPolicy("自定义的跨域策略名称",
            p => p.AllowAnyOrigin())
            );

修改Configure方法
添加

app.UseCors("qwer");//必须位于UserMvc之前
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

香煎三文鱼

你的鼓励将是我创作的最大动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值