zoukankan      html  css  js  c++  java
  • asp net core mvc 跨域ajax解决方案

    1、配置服务端

    在Startup文件中国配置Cors策略:

           IEnumerable<Client> clients= Configuration.GetSection("Clients").Get(typeof(IEnumerable<Client>)) as IEnumerable<Client>;
    
                List<string> urls = new List<string>();
                foreach (var client in clients)
                {
                    urls.AddRange(client.AllowedCorsOrigins);
                }
                services.AddCors(options =>
                {
                    options.AddPolicy("default",
                        builder => builder.WithOrigins(urls.ToArray())
                                        .AllowAnyHeader()
                                        .AllowCredentials()
                                        .AllowAnyMethod());
                });

    启用CORS策略,可以在Startup文件中配置,也可以在具体的ApiController中配置,代码分别如下:

     app.UseCors("default");
        [Authorize]
        [EnableCors("default")]
        public class NavigationMenuController:Controller
        {
            private NavigationMenuService navigationMenuService;
    
            public NavigationMenuController(NavigationMenuService navigationMenuService)
            {
                this.navigationMenuService = navigationMenuService;
            }
        }

    2、JQuery请求

            $.ajax({
                url: 'http://localhost:5000/api/Private/Values/Identity',
                type: 'GET',
                dataType: 'json',
                crossDomain: true,
                xhrFields: {
                    withCredentials: true
                },
                success: function (result) {
                    $('#platformResult').val(JSON.stringify(result));
                }
            });

    红字是关键 ,值得注意的是需要配置 withCredentials,否则请求不会带上Cookie。

    3、 axios请求

          axios({
            url:
            config.authority +
            "/api/xxxxxxxxxx?clientId=" +
            escape(config.client_id),
            method: "GET",
            withCredentials: true
          }).then(function (result) {
            if (result.success == undefined) {
              self.menuItems = result || [];
            }
          });

  • 相关阅读:
    MyEclipse中的几种查找方法
    WebLogic初学笔记
    CountDownLatch源码分析
    linux--句柄相关
    linux命令--wc
    Spring源码解析(九)--再来说说三级缓存
    定位JVM内存泄漏常用命令和方法
    Mybatis整合Spring之MapperFactoryBean怎么拿到的SqlSessionFactory
    Mybatis3.3.0 Po类有LocalDateTime字段报错
    时间范围查询优化技巧
  • 原文地址:https://www.cnblogs.com/shya/p/8947068.html
Copyright © 2011-2022 走看看