【发布时间】:2017-06-12 00:52:34
【问题描述】:
我有一个使用 Angular CLI 创建的 Angular 2 应用程序。这必须调用 .NET 4.6 Web API。这个路线设置让我发疯了。
对于 Angular,输出的默认文件夹是 /dist。 Angular CLI 完成了所有你梦寐以求的缩小和摇树,然后将其 JavaScript 文件和 index.html 输出到该文件夹。
所以如果我运行index.html,这些文件将从同一个文件夹中检索。一切正常,因为index.html 包含这样的标签:
<base href="/">
Web API 项目具有预期的结构,Angular 应用程序是其根目录中的寄生虫。
所以它看起来像这样:
WebAPI_Project
|- App_Start
| |
| |-WebApiConfig.cs
|- Controllers
|- Models
|- src /* This is the root of the Angular app */
| |- app
| | |- core /* These three folders */
| | |- shared /* are for the modules */
| | |- another_module /* used in the app */
| | |- app.component.ts
| | |- app.module.ts
| |- index.html
|- dist /* This is the Angular output folder */
|- index.html
|- main.bundle.js
WebApiConfig.cs 具有默认设置:
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 }
);
}
为了运行 Angular 应用程序,我使用普通的 ng serve,它在 http://localhost:4200 创建一个 Web 服务器。这个 Web 服务器对 Web API 项目一无所知,所以我也需要在 Visual Studio 中运行它,它会在 http://localhost:5200 启动 IIS Express。
这个设置工作得相当好,让我可以利用 Angular CLI 的实时重新加载支持。
对我来说最大的缺点是这种配置与我们对生产的期望不同。在那里,我希望有一个 Web 服务器 (IIS),同时为 Web API 项目(目前位于 /api/)和 Angular 应用程序(最好位于 /)提供服务。另外,在开发中,我不得不考虑 CORS,而生产设置不会。
为此,我需要更改 WebApiConfig 路由以提供我的静态文件,该文件将位于 /dist/ 下。
对于 ASP.NET Core 和 MVC 4,有许多文章展示了我应该如何在 Startup.cs 中使用 Microsoft.AspNetCore.StaticFiles(或 Microsoft.AspNet.StaticFiles)。基本上,将以下两行添加到Configure 函数中:
public void Configure(IApplicationBuilder app, IHostingEnvironment env,
ILoggerFactory loggerFactory)
{
// Other stuff
// Two new lines
app.UseStaticFiles();
app.UseDefaultFiles();
app.UseMvc(m =>
{
// Other routes specified here
});
}
问题是我既不使用 ASP.NET Core 也不使用 MVC。
尽管 Web API 显然是没有视图的 MVC,但 Web API 项目只带有 WebApiConfig.cs 文件,没有 Startup.cs 和 `IApplicationBuilder'。
我尝试将此行添加到我的 Register 函数中:
config.Routes.IgnoreRoute("StaticFiles", "*.html");
这服务于 index.html(但在 localhost:5200/dist/index.html),但它找不到它的任何资产,因为 base href="/"。我可以在 index.html 中更改它,但随后 ng serve 会中断。
我认为我需要以下两件事之一:
- 一种创建路由的方法,以便对
/index.html的引用服务于/dist/index.html,或者 - 一种使用前面提到的 StaticFiles 程序集的方法。
那我该怎么做呢?
【问题讨论】:
标签: angular asp.net-web-api url-routing angular-cli asp.net-web-api-routing