【问题标题】:Angular 2 routing with ASP .Net Core (non-mvc)带有 ASP .Net Core(非 mvc)的 Angular 2 路由
【发布时间】:2016-07-22 17:05:58
【问题描述】:

我正在尝试使用 .net core 和 Angular 2 设置路由,但路由无法解析,因为它们已由服务器解析。

我见过的一个解决方案是注册一个默认路由到你的家庭控制器或其他东西......但我没有任何 MVC 控制器。

我已将此添加到我的主要组件中(并完成了所有其他路由器先决条件)

@RouteConfig([
    { path: '/', name: 'Table', component: TableComp, useAsDefault: true },
    { path: '/login', name: 'Login', component: LoginComp }
])

而且我在 startup.cs 中确实有这些:

在 ConfigureServices() 中

services.AddMvc();

在 Configure() 中

app.UseMvc();

但是由于我实际上并没有使用任何 MVC 控制器或注册任何 MVC 路由,我不知道如何让我的角度路由在浏览器而不是服务器中解析,以及为什么它们不是只是做事......

【问题讨论】:

  • 我建议使用单个 MVC 控制器来提供单个 Index.cshtml 视图。这允许您利用 asp.net 内置的路由和标签助手。

标签: asp.net asp.net-mvc angular asp.net-core


【解决方案1】:

以下配置应该适合大多数在 .NET Core 中使用客户端路由的项目:

DefaultFilesOptions options = new DefaultFilesOptions();
options.DefaultFileNames.Clear();
options.DefaultFileNames.Add("index.html");

app.Use(async (context, next) =>
{
    await next();

    if (context.Response.StatusCode == 404 && !Path.HasExtension(context.Request.Path.Value))
    {
        context.Request.Path = "/index.html";
        await next();
    }
})
.UseCors("AllowAll")
.UseMvc()
.UseDefaultFiles(options)
.UseStaticFiles();

【讨论】:

  • 这会被添加到 RouteConfig 中还是什么?或者我会将它添加到哪个文件中?
  • 经过测试并且有效。这也适用于没有 UseCors 和 UseMvc 的情况。
  • @Brett 这应该添加到 de Startup.Configure 方法变量 app 是 IApplicationBuilder
  • 请注意,如果有人感到困惑:Path 来自 System.IO 命名空间。
【解决方案2】:

您正在寻找在this github 存储库中找到的Microsoft.AspNetCore.SpaServices。寻找这个example

app.UseStaticFiles();

app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "default",
        template: "{controller=Home}/{action=Index}/{id?}");

    routes.MapSpaFallbackRoute(
        name: "spa-fallback",
        defaults: new { controller = "Home", action = "Index" });
});

这里有一个older post 与一些以前的版本,但设置应该非常相似。

【讨论】:

    【解决方案3】:

    试试这个example Asp Core + Angular2 + Swashbuckle + Docker。

    它将UseMvc() 用于 C# API 控制器。和 UseStaticFiles() 提供 AngularJs(和其他静态)文件。

    因此,您将 Asp Core 后端作为服务运行。使用 Webpack,您可以从 Typescript 源代码构建 AngularJs 应用程序。它将被发布到public 文件夹后端看起来提供静态数据。

    【讨论】:

      【解决方案4】:

      我将 index.html 放在 wwwroot 中,并在启动页面中使用 DefaultFiles()。网络服务器知道并自动找到默认文件 - index.html。

      public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
          {
      
              app.UseDefaultFiles();
              app.UseStaticFiles();
      
              app.UseMvc();
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-04-06
        • 2017-08-01
        • 1970-01-01
        • 1970-01-01
        • 2017-07-06
        • 2021-01-11
        • 2019-07-10
        相关资源
        最近更新 更多