.NetCore【中间件】跨域CORS
CORS
前后端分离部署需要跨域设置
Core中如何设置CORS
- 中间件
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
namespace Thomerson.Gatlin.Midware
{
/// <summary>
/// 跨域设置
/// </summary>
public static class CORSMidware
{
public static readonly string PolicyName = "AppDomain";
public static IServiceCollection AddCorsMidware(this IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy(PolicyName, builder =>
{
builder
//.WithOrigins("http://127.0.0.1:65356", "http://localhost:65356")
.AllowAnyOrigin() // Allow access to any source from the host
.AllowAnyMethod() // Ensures that the policy allows any method
.AllowAnyHeader() // Ensures that the policy allows any header
.AllowCredentials(); // Specify the processing of cookie
});
});
return services;
}
public static IApplicationBuilder UseCORSMidware(this IApplicationBuilder app)
{
app.UseCors(PolicyName);//必须位于UserMvc之前
return app;
}
}
}
- startup中配置中间件
//跨域设置
services.AddCorsMidware();
//全局的跨域设置 必须位于UserMvc之前
app.UseCORSMidware();
- API如何设置可跨域
Controller
中加上EnableCors
特性
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
namespace Thomerson.Gatlin.Controllers
{
/// <summary>
/// Base API Controller
/// </summary>
[Route("api/[controller]")]
[ApiController]
[EnableCors("AppDomain")] //路由跨域设置 AppDomain = CORSMidware.PolicyName
public class BaseAPIController : ControllerBase
{
}
}