我假设您在 Visual Studio 2015 上使用 ASP.NET MVC 和解决方案根目录中的 index.html 开发解决方案,文件/文件夹结构至少如下:
- /Controllers
- index.html
- /src/app/ (Angular source)
- web.config
第一步:web.config配置
将以下 rewrite rules 添加到 web.config 的 system.webServer 部分:
<system.webServer>
<rewrite>
<rules>
<rule name="clientRewrite rule" stopProcessing="true">
<match url=".*" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_URI}" matchType="Pattern" pattern="^/api/" ignoreCase="true" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_URI}" matchType="Pattern" pattern="^/assets/" ignoreCase="true" negate="true" />
</conditions>
<action type="Rewrite" url="/" />
</rule>
</rules>
</rewrite>
</system.webServer>
此配置会将所有请求(/api 和 /assets 除外)重定向到您的 index.html。您可以自定义此行为。
另外,不要忘记在appSettings 中启用webpages:
<add key="webpages:Enabled" value="false" />
编辑
在system.web`编译`部分中为html 扩展添加buildProviders。
<buildProviders>
<add extension=".html" type="System.Web.WebPages.Razor.RazorBuildProvider, System.Web.WebPages.Razor" />
</buildProviders>
第 2 步:index.html
确保在 index.html 中包含base href,位于<head> ... </head> 标记之间:
<base href="/">
第 3 步:Global.asax 配置
您需要注册html 分机。只需将以下方法添加到 Global.asax.cs:
public static void RegisterHtmlExtension()
{
RazorCodeLanguage.Languages.Add("html", new CSharpRazorCodeLanguage());
WebPageHttpHandler.RegisterExtension("html");
}
并在Application_Start() 方法中调用RegisterHtmlExtension();。
您无需为angular views(模板)注册路由。以下(最小)服务器路由配置就足够了:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("favicon.ico");
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
//register custom routes (extensions, etc)
var routePublisher = EngineContext.Current.Resolve<IRoutePublisher>();
routePublisher.RegisterRoutes(routes);
}
如果您有 WebAPI 控制器,您可能需要为它们进行适当的路由配置。此配置应该可以工作:
public static class WebApiRouteProvider
{
public static void Register(HttpConfiguration config)
{
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
"DefaultApi",
"api/{controller}/{id}",
new { area = "api", id = RouteParameter.Optional }
);
}
}
而且,您必须通过在Application_Start() 方法中调用GlobalConfiguration.Configure(WebApiRouteProvider.Register); 来注册这些路由。
结论
这样,您将能够将所有请求重定向到您的 index.html(重写规则中明确定义的路径除外)。
而且,Angular 将能够拦截具有给定路径的所有请求(例如:http://yoursite.com/about/us、http://yoursite.com/account/login 等),这将导致呈现具有给定路由的组件。