1.打开 Program.cs 文件,在 var app = builder.Build(); 语句前添加如下代码
builder.Services.AddCors(o => o.AddPolicy("any", p => p.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod()));
2.在var app = builder.Build();语句后添加 app.UseCors();
app.UseCors();
Program.cs完整代码如下
var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); builder.Services.AddCors(o => o.AddPolicy("any", p => p.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod())); var app = builder.Build(); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseCors(); app.UseHttpsRedirection(); app.UseAuthorization(); app.MapControllers(); app.Run();
3.使用
在定义接口的地方引入 [EnableCors("any")] any 为
builder.Services.AddCors(o => o.AddPolicy("any", p => p.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod())); 里定义的 any
完整代码如下
using Microsoft.AspNetCore.Cors; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using SpingSystem_API.Model; namespace SpingSystem_API.Controllers { [EnableCors("any")] [Route("api/[controller]/[action]")] [ApiController] public class ProductsController : ControllerBase { public List<Products> GetProduct() { List<Products> productsList = Products.GetProductList(); return productsList; } } }
标签:webapi,跨域,app,any,var,Services,using,net,builder From: https://www.cnblogs.com/tlfe/p/18205443