.NET 6 跨域请求处理 405错误
一、背景
项目中,使用前后端分离的模式进行开发时,前端请求后端接口的时候,有时候会报405错误,请求方式为option。
这是由于接口请求跨域了导致的,在后台配置跨域策略即可。
二、为什么会有跨域?
浏览器对Ajax请求做的安全限制。
三、NET6配置跨域
在program.cs上添加如下代码
var builder = WebApplication.CreateBuilder(args);
//添加跨域请求处理配置
builder.Services.AddCors(options =>
{
options.AddDefaultPolicy(
builder =>
{
builder.AllowAnyOrigin()
.SetPreflightMaxAge(TimeSpan.FromSeconds(2520))
.AllowAnyHeader().AllowAnyMethod();
});
});
var app = builder.Build();
//启用跨域请求
app.UseCors();

浙公网安备 33010602011771号