• ASP.NET CORE 3.1 跨域中间件


    using Microsoft.AspNetCore.Http;
    using System.Threading.Tasks;
    
    namespace Core.Api
    {
        /// <summary>
        /// 跨域中间件
        /// </summary>
        public class CorsMiddleware
        {
            private readonly RequestDelegate _next;
    
            /// <summary>
            /// 管道执行到该中间件时候下一个中间件的RequestDelegate请求委托,如果有其它参数,也同样通过注入的方式获得
            /// </summary>
            /// <param name="next">下一个处理者</param>
            public CorsMiddleware(RequestDelegate next)
            {
                _next = next;
            }
    
            /// <summary>
            /// 自定义中间件要执行的逻辑
            /// </summary>
            /// <param name="context"></param>
            /// <returns></returns>
            public async Task Invoke(HttpContext context)
            {
                context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
                context.Response.Headers.Add("Access-Control-Allow-Headers", context.Request.Headers["Access-Control-Request-Headers"]);
                context.Response.Headers.Add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
    
                //若为OPTIONS跨域请求则直接返回,不进入后续管道
                if (context.Request.Method.ToUpper() != "OPTIONS")
                    await _next(context);//把context传进去执行下一个中间件
            }
        }
    }
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseMiddleware<CorsMiddleware>()//跨域
    }

     利用ajax跨域请求调用:需要加头部请求

    headers: {
      'Content-Type': 'application/json;charset=utf-8'
    }

    后台是类对象:

    ajax向后台传递参数为对象实例:

    data: JSON.stringify({
            'username': name,
            'password': pwd
        }),
    <script>
        function btntest() {
            $.ajax({
                type: 'post',
                url: 'http://localhost:5000/Base_Manage/Home/SubmitLogin',
                dataType: 'json',
                data: JSON.stringify({
                    'userName':'admin',
                    'password': '123456'
                }),
                contentType: false,
                headers: {
                    'Authorization': '',
                    'Content-Type': 'application/json;charset=utf-8'
                   
                },
                success: function (res) {
                    
                    console.log(res);
                },
                error: function (err) {
                    reject(err)
                }
            });
        }
    </script>
    View Code


  • 相关阅读:
    cat > file << EOF 的用法
    jemter参数化是如何取值的?(数据分配)
    使用elasticdump迁移es数据
    阿里云SLB的http强制转https
    Centos7主机安装Cockpit管理其他主机
    CentOS 7配置Chrony服务进行时间同步
    Nginx负载均衡设置max_fails和fail_timeout
    openresty(nginx) 配置 stream 转发
    rabbitmq的内存节点和磁盘节点
    nginx实现vue的web页面项目集群负载
  • 原文地址:https://www.cnblogs.com/smileZeng/p/13585264.html
Copyright © 2020-2023  润新知