本地IIS中Context.Request.Path未包含应用名称的问题
IIS本地环境获取含应用名称URL的解决办法
问题现象
本地IIS环境下,使用asp-route-returnUrl="@Context.Request.Path"生成表单时:
- 浏览器URL为
http://localhost/myapp,Context.Request.Path返回空值 - URL为
http://localhost/myapp/act1,仅返回/act1
需要拿到包含应用名myapp的完整路径部分。
可行方案
拼接PathBase和Path:
PathBase会自动获取IIS里配置的应用虚拟路径(即/myapp),和Path组合就能得到完整路径<form id="lang" ... asp-route-returnUrl="@($"{Context.Request.PathBase}{Context.Request.Path}")" method="post">访问
http://localhost/myapp时返回/myapp,访问/myapp/act1时返回/myapp/act1。直接使用GetEncodedPathAndQuery():如果需要携带查询字符串,这个方法能直接返回含应用名的完整路径加参数
<form id="lang" ... asp-route-returnUrl="@Context.Request.GetEncodedPathAndQuery()" method="post">比如访问
http://localhost/myapp?foo=bar,会返回/myapp?foo=bar。手动指定应用名(不推荐):如果应用名固定,也可以硬编码拼接,但应用名变更后需同步修改代码,灵活性差
<form id="lang" ... asp-route-returnUrl="@($"/myapp{Context.Request.Path}")" method="post">
注意点
- 确保IIS里的应用程序虚拟路径配置正确,
PathBase的值完全依赖该配置 - 若在开发服务器(如Kestrel)测试,可通过启动参数
--urls=http://localhost/myapp模拟IIS的虚拟路径环境
内容的提问来源于stack exchange,提问作者buga
相关产品推荐
相关产品推荐

