【问题标题】:Serving angular with routes in asp.net core 2 project在 asp.net core 2 项目中使用路由服务角度
【发布时间】:2018-05-29 14:01:53
【问题描述】:

我有一个 Angular 项目,我使用 cli "ng build --prod" 构建并放入我想要为该站点提供服务的 asp.net 核心项目的 wwwroot 目录中。 asp 项目没有我正在使用的 MVC 控制器,因此我不必考虑这一点。

我将应用程序设置为使用默认文件和静态文件。当我导航到服务器根目录时,这给了我 Angular 应用程序,在本例中为 localhost:5000 => (delivers) index.html。从那里我可以使用应用程序和路由工作。

但是当我尝试手动链接到任何路线时(例如,输入http://localhost:5000/quality-test-list)我只会得到一个没有任何内容的白页。

我的猜测是服务器端路由禁止这样做。 我查看了标准的“dotnet new angular”项目文件,但我无法弄清楚。

我的启动文件:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        app.UseDefaultFiles();
        app.UseStaticFiles();

    }
}

【问题讨论】:

  • 尝试关注this tutorial
  • @ElmerDantas 该链接已失效。
  • 再次检查。最后你会找到你想要的。秘诀就是将任何“未找到”路由重定向到您的 index.html
  • @ElmerDantas 谢谢,解决了!如果你愿意,你可以用指南中的代码写一个答案,我可以把它标记为正确的。
  • 完成!我刚刚写信是因为您已经问过了,但我很确定存在另一种方式(更好的方式)来解决这个问题。每次遇到 404 错误时,在 IIS 上创建规则或仅重定向到主路由“index.html”。当我写这篇文章时,我是从 angular + .core 开始的,所以它必须改进(但我还没有时间去做,哈哈)。很高兴为您提供帮助!

标签: c# angular asp.net-core


【解决方案1】:

在您的配置部分,使用app.use 方法将所有404 配置为您的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();
              }
    })
    .UseDefaultFiles(new DefaultFilesOptions { DefaultFilesName = new List<string>{ "index.html" } })
    .UseStaticFiles(new StaticFilesOptions 
                    {
                       FileProvider = new PhysicalFileProvider(
                           Path.Combine(Directory.GetCurrentDiretory(), "@wwwroot")),
                           RequestPath = new PathString("")
    })
    .UseMvc();

【讨论】:

    猜你喜欢
    • 2016-10-19
    • 1970-01-01
    • 2017-05-06
    • 2019-01-10
    • 1970-01-01
    • 2018-08-25
    • 2018-10-12
    • 1970-01-01
    • 2021-04-01
    相关资源
    最近更新 更多