如何更改 ASP.Net WebAPI 应用程序的根路径? [英] How do I change the root path of a ASP.Net WebAPI application?
问题描述
我正在尝试创建一个结合 ASP.NET WebAPI 和 Yeoman Angluarjs 生成器的单页 Web 应用程序.目前我有一个如下所示的项目结构
I am trying create a single page web app combining both ASP.NET WebAPI and the Yeoman Angluarjs generator. Currently I have a project structure as laid out below
|-- yeomanAngularApp|-- 应用|-- 分布|-- 脚本|-- index.html|-- 等等...|-- WebApiApp|-- App_Start|-- 斌|-- 内容|-- 控制器|-- 模型|-- WebApiApp.csproj|-- 分布|-- 脚本|-- index.html
当我想构建应用程序分发时,我将 yeomanAngularApp
中的 dist
文件夹复制到 WebApiApp
中,替换了 dist
文件夹在那里.
When I want to build the app distribution, I copy the dist
folder in the yeomanAngularApp
into the WebApiApp
replacing the dist
folder in there.
现在这一切都很容易做到.我真正想要做的是告诉 WebApiApp
不要使用 WebApiApp
作为项目的根,而是使用 WebApiAppdist
.这意味着我可以去 http://localhost/index.html
而不是去 http://localhost/dist/index.html
,即使 index.html
位于 dist
文件夹中.最重要的是,我还希望控制器的 WebAPI 路由也能很好地发挥作用.
Now this is all very easy to do. What I really then want to do is to tell the WebApiApp
not to use WebApiApp
as the root of the project, but use WebApiAppdist
. This means instead of going to http://localhost/dist/index.html
, I could go to http://localhost/index.html
even though index.html
is in the dist
folder. On top of this I would also like my WebAPI routing for the controllers to play nicely too.
我已经搜索了一段时间,但似乎找不到答案.我能想到的最好的方法是使用 URL 重写,我觉得这不太对.
I've been searching for a while and I can't seem to find an answer. The best I can come up with, is using URL rewriting, which to me doesn't feel right.
推荐答案
URL 重写正是您想要的,使用条件块来测试文件是否存在.dist
目录下的内容是静态的(即存在于文件系统中),但 WebApiApp
路由是动态的.因此,您只需要测试路由是否与 dist
目录中存在的文件匹配,如果不匹配,则简单地让 .NET 处理路由.将以下内容添加到 <system.webServer>
部分中的 Web.config
文件应该可以解决问题:
URL rewriting is exactly what you want, with a condition block to test if the file exists. The content under your dist
directory is static (i.e. lives on the file system) but the WebApiApp
routes are dynamic. So you simply need to test if the route matches a file that exists in the dist
directory or not, if not simply let .NET handle the route. Adding the following to your Web.config
file within the <system.webServer>
section should do the trick:
<rewrite>
<rules>
<rule name="static dist files" stopProcessing="true">
<match url="^(.+)$" />
<conditions>
<add input="{APPL_PHYSICAL_PATH}dist{R:1}" matchType="IsFile" />
</conditions>
<action type="Rewrite" url="/dist/{R:1}" />
</rule>
<rule name="index.html as document root" stopProcessing="true">
<match url="^$" />
<action type="Rewrite" url="/dist/index.html" />
</rule>
</rules>
</rewrite>
第二条规则是可选的,但这意味着对您站点根目录的请求仍将提供 dist
目录中的 index.html
文件,从而有效地使根项目 WebApiAppdist
但仍允许所有 WebAPI 路由.
The second rule is optional but it means a request for the root of your site will still serve the index.html
file from the dist
directory, effectively making the root of the project WebApiAppdist
but still allowing all WebAPI routing.
这篇关于如何更改 ASP.Net WebAPI 应用程序的根路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!