1

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

1
  • I had the code above after app.UseStaticFiles(); After I changed the order and put app.UseStaticFiles(); after the code above it works. Commented Dec 6, 2016 at 14:20

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.