首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何将Web API以外的所有内容路由到/index.html

如何将Web API以外的所有内容路由到/index.html
EN

Stack Overflow用户
提问于 2013-10-29 03:03:34
回答 6查看 35.2K关注 0票数 55

我一直在做一个AngularJS项目,在ASP.NET MVC内部使用Web。它工作得很好,除非您尝试直接转到angular路由的URL或刷新页面。我认为这是我可以用MVC的路由引擎来处理的事情,而不是摆弄服务器配置。

当前WebAPIConfig:

代码语言:javascript
复制
public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional },
            constraints: new { id = @"^[0-9]+$" }
        );

        config.Routes.MapHttpRoute(
            name: "ApiWithActionAndName",
            routeTemplate: "api/{controller}/{action}/{name}",
            defaults: null,
            constraints: new { name = @"^[a-z]+$" }
        );

        config.Routes.MapHttpRoute(
            name: "ApiWithAction",
            routeTemplate: "api/{controller}/{action}",
            defaults: new { action = "Get" }
        );
    }
}

当前RouteConfig:

代码语言:javascript
复制
public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.IgnoreRoute(""); //Allow index.html to load
        routes.IgnoreRoute("partials/*"); 
        routes.IgnoreRoute("assets/*");
    }
}

当前Global.asax.cs:

代码语言:javascript
复制
public class WebApiApplication : HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        GlobalConfiguration.Configure(WebApiConfig.Register);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        var formatters = GlobalConfiguration.Configuration.Formatters;
        formatters.Remove(formatters.XmlFormatter);
        GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings = new JsonSerializerSettings
        {
            Formatting = Formatting.Indented,
            PreserveReferencesHandling = PreserveReferencesHandling.None,
            ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
        };
    }
}

目标:

/api/*继续转到WebAPI,/partials/和/assets/都转到文件系统,其他任何内容都会路由到/index.html,这是我的Angular单页应用程序。

编辑----

我好像把它弄好了。将此代码添加到RouteConfig.cs的底部:

代码语言:javascript
复制
 routes.MapPageRoute("Default", "{*anything}", "~/index.html");

下面是对根web.config的更改:

代码语言:javascript
复制
<system.web>
...
  <compilation debug="true" targetFramework="4.5.1">
    <buildProviders>
      ...
      <add extension=".html" type="System.Web.Compilation.PageBuildProvider" /> <!-- Allows for routing everything to ~/index.html -->
      ...
    </buildProviders>
  </compilation>
...
</system.web>

然而,它闻起来像是黑客。有没有更好的方法呢?

EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2013-10-29 03:10:58

使用通配符段:

代码语言:javascript
复制
routes.MapRoute(
    name: "Default",
    url: "{*anything}",
    defaults: new { controller = "Home", action = "Index" }
);
票数 27
EN

Stack Overflow用户

发布于 2014-06-17 17:48:06

建议更本地化的方法

代码语言:javascript
复制
<system.webServer>
    <httpErrors errorMode="Custom">
        <remove statusCode="404" subStatusCode="-1"/>
        <error statusCode="404" prefixLanguageFilePath="" path="/index.cshtml" responseMode="ExecuteURL"/>
    </httpErrors>
</system.webServer>
票数 12
EN

Stack Overflow用户

发布于 2016-10-05 04:15:16

在我的例子中,这些方法都不起作用。我陷入了2个错误消息的地狱。这种类型的页面不是就是某种类型的404。

url重写成功:

代码语言:javascript
复制
<system.webServer>
    <rewrite>
      <rules>
        <rule name="AngularJS" stopProcessing="true">
          <match url="[a-zA-Z]*" />

          <conditions logicalGrouping="MatchAll">
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
            <add input="{REQUEST_URI}" pattern="^/(api)" negate="true" />
          </conditions>
          <action type="Rewrite" url="/" />
        </rule>
      </rules>
    </rewrite>
    ...

请注意,我匹配的是a-zA-Z,因为我不想重写任何.js、.map等urls。

这在VS开箱即用,但是在IIS中你可能需要安装一个url重写模块https://www.iis.net/downloads/microsoft/url-rewrite

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19643001

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档