.Net Core3.1下WebApi跨域的处理

在.Net Core3.1下WebApi跨域的处理比在.Net Core2.1时复杂的多了
1.在Startup类种的ConfigureServices方法中增加

services.AddCors(
                    options => options.AddPolicy("AllowCors",
                    p => p.WithOrigins("http://*.*.*.*","http://localhost:8080")
                    //p.AllowAnyOrigin()
                    .AllowAnyHeader()
                    .AllowAnyMethod()
                    //.AllowCredentials()//.net 2.1下可以使用
                    )

注意AllowCredentials()此方法在.net core2.1下可以使用在.net core3.1下就不行了。

2.在Configure方法中

//配置Cors 放在UseRouting和UseEndpoints之间
            app.UseCors("AllowCors");

注意此方法要放在app.UseRouting()和app.UseEndpoints()之间
在这里插入图片描述
3.自定义中间件

using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace MyMis.MvcExtend.MiddleWare {
    public class CorsMiddleware {
        private readonly RequestDelegate _next;
        public CorsMiddleware(RequestDelegate next) {
            _next = next;
        }

        public async Task Invoke(HttpContext context) {
            //if (!context.Response.Headers.ContainsKey("Access-Control-Allow-Origin")) {
                //context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
            //}
            if (!context.Response.Headers.ContainsKey("Access-Control-Allow-Credentials")) {
                context.Response.Headers.Add("Access-Control-Allow-Credentials", "true");
            }
            await _next(context);
        }
    }
}
using Microsoft.AspNetCore.Builder;
using System;
using System.Collections.Generic;
using System.Text;

namespace MyMis.MvcExtend.MiddleWare {
    public static class CorsMiddlewareExtension {
        /// <summary>
        /// 跨域配置中间件
        /// </summary>
        /// <param name="app"></param>
        /// <returns></returns>
        public static IApplicationBuilder UseCorsAllowOrigin(this IApplicationBuilder app) {
            return app.UseMiddleware<CorsMiddleware>();
        }
    }
}

然后在Startup类种的Configure方法的开头中注册

            app.UseCorsAllowOrigin();//配置Cors

使用Vue前段调用后端.net core3.1开发的一直会提示Access-Control-Allow-Credentials这个有错误,在.net core2.1的时候注册时可以使用AllowCredentials()但是现在不行了,后来就在定义的中间件上请求头上加上这个这样就可以了

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值