Reputation: 11
I have an ASP.Net core app that is used only for web API and has Angular 2 front end. When I added routing to angular app and navigate to some route in Angular it navigates, but when I do a refresh of the page, I get page not found error. I have the following in configure method
app.Use(async (context, next) =>
{
await next();
if (context.Response.StatusCode == 404
&& !Path.HasExtension(context.Request.Path.Value))
{
context.Request.Path = "/index.html";
context.Response.StatusCode = 200;
await next();
}
});
I tried to add rewrite rules like in Angular2 routing with Asp.net 4.5
I get client side errors, when I do that
Uncaught SyntaxError: Unexpected token <
Any help is appreciated. Thanks
Upvotes: 1
Views: 1115
Reputation: 4071
Your code is more of an ugly fix than a real management.
You need to make it so that your route is managed server-side and then managed correctly from your client-side as you want it.
As I was using MVC in my ASP.NET / Angular2 project, I made it so that my URLs that would not be API calls would be managed with a FallBackRoute.
app.UseMvc(r =>
{
r.MapRoute(
name: "default",
template: "{controller}/{path?}/{action}/{id?}",
defaults: new { controller = "Home", action = "Index" }
);
r.MapSpaFallbackRoute(
name: "spa-fallback",
defaults: new { controller = "Home", action = "Index" }
);
});
That way, on refresh or manual URL load, my index.cshtml would be loaded and load the Angular2 Core that would then manage the wanted route with the router.
This is imho a better thing to do than watching for 404 errors.
Upvotes: 4