如何更改ASP.Net WebAPI应用程序的根路径?

时间:2014-07-16 11:51:23

标签: asp.net asp.net-web-api

我正在尝试创建一个结合ASP.NET WebAPI和Yeoman Angluarjs生成器的单页Web应用程序。目前我的项目结构如下所示

|-- yeomanAngularApp |-- app |-- dist |-- scripts |-- index.html |-- etc... |-- WebApiApp |-- App_Start |-- bin |-- Content |-- Controllers |-- Models |-- WebApiApp.csproj |-- dist |-- scripts |-- index.html

当我想构建应用程序分发时,我将dist中的yeomanAngularApp文件夹复制到替换WebApiApp文件夹中的dist

现在这很容易做到。我真正想做的是告诉WebApiApp不要使用WebApiApp\作为项目的根,而是使用WebApiApp\dist。这意味着我可以转到http://localhost/dist/index.html,而不是转到http://localhost/index.html,即使index.html位于dist文件夹中。除此之外,我还希望控制器的WebAPI路由能够很好地发挥作用。

我一直在寻找一段时间,我似乎无法找到答案。我能想到的最好的就是使用URL重写,这对我来说感觉不对。

1 个答案:

答案 0 :(得分:24)

URL重写正是您想要的,使用条件块来测试文件是否存在。 dist目录下的内容是静态的(即存在于文件系统中),但WebApiApp路由是动态的。所以你只需要测试路由是否匹配dist目录中存在的文件,如果不是简单地让.NET处理路由。将以下内容添加到Web.config部分中的<system.webServer>文件中应该可以解决问题:

<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>

第二条规则是可选的,但这意味着对您网站的根目录的请求仍会提供index.html目录中的dist文件,从而有效地创建项目的根目录WebApiApp\dist但仍允许所有WebAPI路由。

相关问题