教程参考:
启用CORS有三种方法:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
//多个url用豆号隔开,url为站点的地址,可以将发布后的地址也同时配置上
"CorsUrls": "http://example.com,http://www.contoso.com"
}
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
//必须appsettings.json中配置
string corsUrls = Configuration["CorsUrls"];
if (string.IsNullOrEmpty(corsUrls))
{
throw new Exception("请配置跨请求的前端Url");
}
services.AddCors(options =>
{
options.AddDefaultPolicy(
builder =>
{
builder.WithOrigins(corsUrls.Split(","))
//添加预检请求过期时间
.SetPreflightMaxAge(TimeSpan.FromSeconds(2520))
.AllowCredentials()
.AllowAnyHeader().AllowAnyMethod();
});
});
// services.AddResponseCaching();
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseCors();//必须将对的调用 UseCors 置于UseRouting之后 但在UseAuthorization之前 原因可查阅;https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/middleware/?view=aspnetcore-3.1#middleware-order
// app.UseResponseCaching();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
这样,就已经配置好了,前端直接请求就行了。
asp.net core api 前后端分离中配置跨域(cors)
原文:https://www.cnblogs.com/Z7TS/p/13883941.html