如何在IIS上共同发布Angular与ASP.NET Core Web API项目
解决方案:IIS下同站点部署Angular与ASP.NET Core API(API为主项目)
核心需求梳理
- ASP.NET Core Web API作为主项目,处理所有
/api开头的请求 - Angular应用发布到站点根目录的
app文件夹,但需让http://mysite/home这类根路径请求直接由Angular路由处理,URL不能显示/app前缀 - 重写请求时不能暴露
index.html文件名,保持URL不变
修正后的URL重写规则
替换你原有的web.config中<rewrite>节点内容为以下代码:
<configuration> <system.webServer> <rewrite> <rules> <!-- 放行/api开头的请求,交给ASP.NET Core API处理 --> <rule name="API Route" stopProcessing="true"> <match url="^api/(.*)$" /> <action type="None" /> </rule> <!-- 匹配存在的静态文件,重写到app文件夹下的对应文件 --> <rule name="Angular Static Files" stopProcessing="true"> <match url="^(.*)$" /> <conditions logicalGrouping="MatchAll"> <add input="{REQUEST_URI}" pattern="^/api" negate="true" /> <add input="{APPL_PHYSICAL_PATH}app\{R:1}" matchType="IsFile" /> </conditions> <action type="Rewrite" url="/app/{R:1}" /> </rule> <!-- 所有非API、非静态文件的请求,重写到Angular的index.html(保持URL不变) --> <rule name="Angular SPA Route" stopProcessing="true"> <match url="^(.*)$" /> <conditions logicalGrouping="MatchAll"> <add input="{REQUEST_URI}" pattern="^/api" negate="true" /> <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" /> <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" /> </conditions> <action type="Rewrite" url="/app/index.html" /> </rule> </rules> </rewrite> </system.webServer> </configuration>
规则说明
- API Route规则:直接放行
/api开头的请求,让ASP.NET Core管道处理,不做重写 - Angular Static Files规则:非API请求中,如果
app文件夹下存在对应文件名(比如main.js、styles.css),则重写路径到/app/xxx,确保静态资源能正确加载 - Angular SPA Route规则:非API、非静态文件、非目录的请求,全部重写到
/app/index.html,由Angular路由接管,且URL保持不变(因为用的是Rewrite而非Redirect,不会修改地址栏显示)
部署步骤
- 将ASP.NET Core Web API发布到IIS站点的根目录
- 执行
ng build --prod打包Angular应用,把打包后的所有文件放到站点根目录的app文件夹中 - 确保IIS已安装URL重写模块(若未安装,可通过IIS管理器的“模块”功能添加或安装对应组件)
内容的提问来源于stack exchange,提问作者Max Bündchen
相关产品推荐
相关产品推荐

