.netcore3.1 设置可跨域

asp.net core 3.1 的跨域问题,如果沿用2.2版本的方法是行不通的。3.1版本对跨域问题要“严格”很多。

微软官方的解释请如下网址:

启用 ASP.NET Core 中的跨域请求 (CORS) - ASP.NET Core 3.1 安全性 - 找一找教程网

 不能 同时打开

AllowAnyOrigin()  .AllowAnyMethod()  .AllowAnyHeader()  .AllowCredentials());

否则会抛异常。

                   // 会抛下面这个异常:
                    System.InvalidOperationException: Endpoint AnXin.DigitalFirePlatform.WebApi.Controllers.StaticPersonController.Get (AnXin.DigitalFirePlatform.WebApi) contains CORS metadata, but a middleware was not found that supports CORS.
                    Configure your application startup by adding app.UseCors() inside the call to Configure(..) in the application startup code. The call to app.UseAuthorization() must appear between app.UseRouting() and app.UseEndpoints(...).
                       at Microsoft.AspNetCore.Routing.EndpointMiddleware.ThrowMissingCorsMiddlewareException(Endpoint endpoint)
                       at Microsoft.AspNetCore.Routing.EndpointMiddleware.Invoke(HttpContext httpContext)
                       at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
                       at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

那么我们就只开其中的1,2个就行了。以下是我的代码,亲测可用:

1、Startup类里先定义一个全局变量:

  readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";//名字随便起

2、ConfigureServices方法里写如下代码:

//找一找教程网原创文章
          
  services.AddCors(options =>
            {
                options.AddPolicy(MyAllowSpecificOrigins,
                  
                    builder => builder.AllowAnyOrigin()
                    
                    .WithMethods("GET", "POST", "HEAD", "PUT", "DELETE", "OPTIONS")

                    );

            });

3、Configure方法里添加中间件:

 app.UseCors(MyAllowSpecificOrigins);

CORS 中间件必须配置为在对 UseRouting 和 UseEndpoints的调用之间执行。 配置不正确将导致中间件停止正常运行。

写个ajax测试下:

<script type="text/javascript">
    $(function () {
        $.get("https://webapi-dev.zyiz.net/api/Health/POk", function (result) {
            $("#mycontent").html(result);
        });

    });

</script>

到这此就可以了,但是还有些小伙伴还没解决,我是没有遇到这个问题。

最后在控制器中加上下面标记以启动跨域设置,这个方法在试一试。
[EnableCors]

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值