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>