如何将MVC应用程序中的所有路由映射到静态文件?

时间:2013-06-16 09:36:47

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

我目前正在编写单页面应用程序,并希望将所有传入请求(除了/ api / {controller})映射到我的Web应用程序到root中的静态文件(index.html)。前端的WebApi呼叫需要可以访问到/ api的路由。有关如何实现这一目标的任何建议吗?

1 个答案:

答案 0 :(得分:1)

您可以使用IIS 7 url rewrite module。此模块是IIS Express Web服务器的一部分,因此您无需任何特殊操作即可启用它。在生产IIS 7服务器上,您可能需要安装并启用the extension

只需将以下规则添加到<system.webServer>部分:

<system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <modules runAllManagedModulesForAllRequests="true" />
    <rewrite>
      <rules>
        <rule name="Rewrite to index.html">
          <match url="^(?:(?!api\/))" />
          <action type="Rewrite" url="index.html" />
        </rule>
      </rules>
    </rewrite>
    <handlers>
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
</system.webServer>

此外,由于您没有使用ASP.NET MVC,因此您可以删除~/App_Start/RouteConfig.cs文件,因为您没有任何MVC控制器。只需保留~/App_Start/WebApiConfig.cs,您将拥有映射到Web API控制器的~/api端点的路由:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}
相关问题