首页 文章

使用ASP .Net Core(非mvc)进行Angular 2路由

提问于
浏览
2

我正在尝试使用.net核心和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路由,我不知道如何在浏览器而不是服务器中解析我的角度路由,以及为什么他们不只是在做事情...

4 回答

  • 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();
    
  • 12

    您正在寻找this github repo中的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以及一些以前的版本,但设置应该非常相似 .

  • 0

    试试这个example Asp Core Angular2 Swashbuckle Docker .

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

    所以你运行Asp Core后端作为服务 . 使用Webpack,您可以从Typescript源代码构建AngularJs应用程序 . 它将发布到 public 文件夹后端看起来服务静态 .

  • 0

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

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

相关问题