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

Jam*_*yer 18 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文件夹复制yeomanAngularAppWebApiApp替换该dist文件夹中.

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

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

小智 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>
Run Code Online (Sandbox Code Playgroud)

第二个规则是可选的,但这意味着对站点根目录的请求仍将index.htmldist目录中提供文件,从而有效地构成项目的根目录WebApiApp\dist但仍允许所有WebAPI路由.