.net webapi 處理前端請求跨域問題

龙卷风吹毁停车场發表於2024-05-22
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;
        }
    }
}





相關文章