前言: 通過ABP官網(https://aspnetboilerplate.com)下載ASP.NET Core 2.x + Angular模板項目是按ReStful風格架構Web API和angular前端是分開獨立部署的,我一開始分開部署到IIS後,前端訪問API會產生跨域限制訪問的問題,通過查 ...
前言:
通過ABP官網(https://aspnetboilerplate.com)下載ASP.NET Core 2.x + Angular模板項目是按ReStful風格架構Web API和angular前端是分開獨立部署的,我一開始分開部署到IIS後,前端訪問API會產生跨域限制訪問的問題,通過查閱代碼,其實ABP框架自帶跨域設置訪問,只需要配置一下就可以了,步驟如下:
一 IIS部署
通過ABP官網模板創建項目,然後分別打包前端和後端程式發佈到IIS:
我的後端發佈到:http://localhost:8060/
我的前端發佈到:http://localhost:8080/
F12 報錯 不允許跨域訪問:Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.
二 配置說明
通過查看代碼有兩個配置的地方:
1. 前端配置在src/assets/appconfig.json
{
"remoteServiceBaseUrl": "http://localhost:8060",
"appBaseUrl": "http://localhost:8080"
}
remoteServiceBaseUrl 遠程訪問API URL, appBaseUrl 自身部署後的URL
2. 後端配置在Host項目 appsettings.json
"App": {
"ServerRootAddress": "http://localhost:8060/",
"ClientRootAddress": "http://localhost:8080/",
"CorsOrigins": "http://localhost:8080/"
}
ClientRootAddress 為客戶端站點配置, CorsOrigins 為允許跨域客戶端站點配置,可以有多個用逗號分開,配置在Startup.cs里進行配置
// Configure CORS for angular2 UI services.AddCors(options => { options.AddPolicy(DefaultCorsPolicyName, builder => { // App:CorsOrigins in appsettings.json can contain more than one address separated by comma. builder .WithOrigins(_appConfiguration["App:CorsOrigins"].Split(",", StringSplitOptions.RemoveEmptyEntries) .Select(o => o.RemovePostFix("/")) .ToArray()) .AllowAnyHeader() .AllowAnyMethod(); }); });
三 運行
配置後再次訪問客戶端 訪問成功
如想前後端集成一起部署請查博客:http://www.cnblogs.com/donaldtdz/p/7882316.html