Brett Brett - 1 year ago 79
ASP.NET (C#) Question

Angular 2 routing with Visual Studio & .NET

I completed the "Tour of Heroes" tutorial on Angular 2's website and everything is working great. If I click around, the URL changes and when I refresh, it takes me right where I was before, as you would expect with proper routing.

I want to now use .NET and C# on the backend, so I went through Angular 2's tutorial on getting the project set up with Visual Studio (I was using Sublime Text before). I completed it and got it working, but noticed that the routing only worked when pressing the back/forward buttons. Refreshing didn't work like it did when I just used Sublime and NPM. I went back to the tutorial and found a message at the bottom that concerns me:

"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."!#build-and-run

Does this mean that Angular 2's routing won't work with Visual Studio when I refresh the page no matter what? Is there no hope for Angular 2's routing to fully work when using Visual Studio/.NET/C#?

Answer Source

Angular 2 uses the HTML5 history API. The urls look just like any other site. When you load the .NET backend will try to handle it and if it can't will return 404.

That is not what you want.

You want to return the contents of index.html and let Angular handle the rest.

Note that you don't want to redirect to, if you do that it will load angular but you will lose the current path. That way you will never be able to share links to your site.

I assume that you are using the latest version of .NET Core and Visual Studio's templates.

What you need to do:

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

  • 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;

For more information look here:!#base-href

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download