使用Visual Studio和.NET进行Angular 2路由

3
我在Angular 2的网站上完成了“英雄之旅”教程,一切都很好。如果我点击周围,URL会改变,当我刷新时,它会带我回到之前的位置,这正如预期的那样,具有正确的路由。
现在我想在后端使用.NET和C#,所以我通过Angular 2的教程在Visual Studio中设置了项目(我之前使用Sublime Text)。我完成了设置并使其工作,但注意到只有在按下后退/前进按钮时才能工作路由。刷新不像我之前使用Sublime和NPM时那样工作。我回到教程并发现了一个令我担忧的消息:
“If this application used the Angular router, a browser refresh could return a 404 - Page Not Found. Look at the address bar. Does it contain a navigation url (a "deep link")? We'll have to configure the server to return index.html for these requests. Until we do, remove the navigation path and refresh again." https://angular.io/docs/ts/latest/cookbook/visual-studio-2015.html#!#build-and-run 这是否意味着无论如何,当我刷新页面时,Angular 2的路由在Visual Studio中都无法工作?使用Visual Studio/.NET/C#时,Angular 2的路由没有完全运行的希望吗?

1
请参考这篇文章- http://www.centare.com/tutorial-angular2-mvc-6-asp-net-5/。虽然这篇文章有点旧,但是在ASP.NET Core应用程序中,Angular2路由功能完美运行。 - Sanket
谢谢,我会看一下的。很高兴知道我可以让它工作。 - Bryan
1个回答

4
Angular 2使用HTML5历史记录API,URL看起来与其他站点一样。当你加载http://example.com/posts/23时,.NET后端将尝试处理它,如果无法处理,则返回404错误。

这不是你想要的。

你需要返回index.html的内容,让Angular处理其余部分。

请注意,你不想重定向到http://example.com/index.html,如果这样做,它将加载Angular,但你将失去当前路径。这样,你将永远无法共享站点链接。

我假设你正在使用最新版本的.NET Core和Visual Studio模板。

你需要做的是:

  • Install this NuGet package Microsoft.AspNetCore.StaticFiles
  • Go to Startup.cs and find the Configure method
  • Add these lines before app.UseMvc();

    app.UseDefaultFiles();
    app.UseStaticFiles();
    
  • Add these lines after app.UseMvc();

    app.Run(async context =>
    {
        context.Response.StatusCode = 200;
        context.Response.ContentType = "text/html";
        await context.Response.SendFileAsync("./wwwroot/index.html");
    });
    
  • Add this to the top of the file

    using Microsoft.AspNetCore.Http;
    

更多信息请查看这里:

https://docs.asp.net/en/latest/fundamentals/static-files.html

https://angular.io/docs/ts/latest/guide/router.html#!#base-href


我不知道我是否在使用较旧的.NET或MVC版本,但我搜索了整个项目,没有找到app.UseMvc()的结果。 - Bryan
我正在更新一个现有的.NET项目,因此不能从头开始。 - Bryan
我有一个用于我的Angular 2项目的package.json文件,这是你所指的吗?我搜索了一下,但没有找到project.json文件。 - Bryan
1
所以这是一个旧的.NET项目。你必须编辑你的Web.config文件。等几分钟看看我能找到什么。 - Hristo Kolev
让我们在聊天中继续这个讨论 - Hristo Kolev
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接