zoukankan      html  css  js  c++  java
  • NetCore中跨域策略的一个坑

    事件回顾

    最近,一个一直使用的前后端分离项目部署到某环境时突然报跨域了。首先肯定想到是后端问题。后端用NetCore项目作为网关接收前端请求,并配置了跨域策略。
    使用的跨域策略:

    services.AddCors(options =>
                options.AddPolicy("AllowSameDomain",
                builder => builder.AllowAnyMethod().AllowAnyHeader().AllowAnyOrigin().AllowCredentials())
    );
    
    app.UseCors("AllowSameDomain");
    

    报错:HttpRequest at 'xxx' from origin 'xxx' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.

    问题解决

    网上查阅发现:
    前端使用了 withCredentials: true,而恰恰这个使用是不允许AllowAnyOrigin()的,意思就是不允许返回的Access-Control-Allow-Origin:*。
    于是将跨域策略改为:

    app.UseCors(builder =>
    {
        builder.SetIsOriginAllowed(_ => true)
              .AllowCredentials()
              .AllowAnyHeader();
    });
    

    不再报错

    参考博文:
    https://www.cnblogs.com/May-day/p/13965087.html

  • 相关阅读:
    nuxt实践
    安卓H5软键盘遮挡输入框
    h5复制粘贴板,打开APP功能
    MVC3
    MVC3
    C#高编
    接口的显式实现(转)
    E-Retail 框架学习
    C#高编
    实现DIV居中布局三种途径(转)
  • 原文地址:https://www.cnblogs.com/muphalem/p/14218912.html
Copyright © 2011-2022 走看看