需求:現在一個應用是前后端開發分離,前端使用angular,后端使用 asp.net core 提供api ,開發完成后,現在需要把兩個程序部署在同一個網站下,應該怎么處理?
首先可以參考微軟的官方文檔 Use the Angular project template with ASP.NET Core
.net core 對前后端的部署還是很友好的,主要處理步驟如下:
1.配置服務 在startup中的 ConfigureServices()中聲明
services.AddSpaStaticFiles(configuration => { //angular文件所在文件夾 configuration.RootPath = "client"; });
2. 調用服務,在startup中的 Configure() 方法中聲明
app.UseStaticFiles(); // spa files app.UseSpaStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller}/{action=Index}"); }); //使用服務 app.UseSpa(f => { //f.Options.SourcePath = @"\client"; if (env.IsDevelopment()) {
// 本地調試用 f.UseProxyToSpaDevelopmentServer("http://localhost:4200"); } });
這里要注意, app.usespa要放在 app.usemvc后面,否者前端是調不到后端api的。
3 部署:
前后端分別發布出來,在iis中把后端部署好,同時,在后端的文件夾中建立一個 “client” 文件夾(第一步中的配置),把前端發布好的文件放置到該目錄中就可以了。