@@ -89,13 +89,16 @@ namespace YhCore.WebApi
|
||||
// 对象映射:对应 Java ModelMapper
|
||||
services.AddAutoMapper(typeof(Startup));
|
||||
|
||||
// 跨域策略:任意源 + 任意方法/头,但不允许凭据(无 AllowCredentials)。
|
||||
// 响应回 Access-Control-Allow-Origin: *,浏览器跨域请求不携带 CAS 登录 Cookie
|
||||
// (登录态仅同源请求可用;跨域只能访问免认证接口)。
|
||||
// 跨域策略:来源白名单(appsettings.json Cors:Origins)+ 允许凭据。
|
||||
// 响应回 Access-Control-Allow-Origin: <具体来源> 且 Access-Control-Allow-Credentials: true,
|
||||
// 白名单内前端可用 fetch/XHR credentials:'include' 跨域携带 CAS 登录 Cookie。
|
||||
// 注意:Cors 规范禁止 * 与凭据同用,故不能用 AllowAnyOrigin。
|
||||
var corsOrigins = Configuration.GetSection("Cors:Origins").Get<string[]>() ?? Array.Empty<string>();
|
||||
services.AddCors(options => options.AddPolicy("default", builder => builder
|
||||
.AllowAnyOrigin()
|
||||
.WithOrigins(corsOrigins)
|
||||
.AllowAnyMethod()
|
||||
.AllowAnyHeader()));
|
||||
.AllowAnyHeader()
|
||||
.AllowCredentials()));
|
||||
|
||||
// 数据层:默认 SQL Server 主库,DatabaseProvider=MySql 可切换
|
||||
services.AddDataLayer(Configuration);
|
||||
@@ -207,7 +210,7 @@ namespace YhCore.WebApi
|
||||
// CORS 中间件必须位于 UseRouting 之后、UseEndpoints 之前(endpoint-aware 模式):
|
||||
// 否则带 [EnableCors] 元数据的控制器端点执行时抛 InvalidOperationException
|
||||
// "contains CORS metadata, but a middleware was not found that supports CORS"(曾导致 GetUserInfo code6)。
|
||||
app.UseCors("AllowSpecificOrigin");
|
||||
app.UseCors("default");
|
||||
|
||||
// 启用 ASP.NET Core Session(需在 UseEndpoints 之前、且在使用 Session 的组件之前注册)。
|
||||
// 仅 Logout 真正读写;其余请求不触碰 Session,不会额外下发 .AspNetCore.Session Cookie。
|
||||
|
||||
@@ -48,5 +48,11 @@
|
||||
"Microsoft.AspNetCore.Authentication": "Information"
|
||||
}
|
||||
},
|
||||
"AllowedHosts": "*"
|
||||
"AllowedHosts": "*",
|
||||
"Cors": {
|
||||
"Origins": [
|
||||
"http://localhost:51835",
|
||||
"http://localhost:8103"
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user