zoukankan      html  css  js  c++  java
  • .netcore3.1 设置可跨域

    本文为原创文章.首发:http://www.zyiz.net/

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

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

    http://www.zyiz.net/tutorial/detail-4801.html 

     不能 同时打开

    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>

     效果如下:

  • 相关阅读:
    Linux iptables 配置规则
    Java之品优购课程讲义_day06(7)
    TCP的三次握手与四次挥手
    区块链挖矿演变史,一键挖矿逐渐成主流
    Java KeyStore 用命令生成keystore文件
    SpringBoot | 第六章:常用注解介绍及简单使用
    PHP开发模式之-单例模式
    Ansible笔记
    CentOS7中搭建cobbler自动装机服务
    号称“新至强,可拓展,赢当下”的Xeon可拓展处理器有多逆天?
  • 原文地址:https://www.cnblogs.com/puzi0315/p/12197612.html
Copyright © 2011-2022 走看看