0

I am trying to implement deep linking in Angular 2. I have completely removed MVC from my client as I've discovered that there's very little it offers me. However, doing that means that I no longer have use of the MVC router.

Can someone please tell me how to get Angular 2 deep linking working without using MVC?

My sample app is located at https://github.com/tonywr71/Snazzle

1 Answer 1

1

You need to rely on the Angular router. In general you need to serve only index.html (or whatever is defaut) from your server for each request (or you can filter for 404 status and send index.html in that case only). Angular will do the rest.

To catch 404 and redirect in the asp.net core apllication you can add this to your Configure method in the Startup.cs file:

app.Use(async (context, next) =>
{
    await next();
    if(context.Response.StatusCode == 404)
    {
        context.Request.Path = "/";
        await next();
    }
});
Sign up to request clarification or add additional context in comments.

4 Comments

Yea I know I need to rely on the Angular router. But its the interception that I need to know more about. Also, isn't a 404 a bit inefficient, because it is doing the check first instead of redirecting all externally provided (non angular2) urls to the one place?
I saw this bit of code, which I put in Configure in Startup.cs after the UseStaticFiles call, but it didn't work: app.Use(async (context, next) => { await next(); if (context.Response.StatusCode == 404 && !Path.HasExtension(context.Request.Path.Value)) { context.Request.Path = "/cats-by-owner-gender"; // Put your Angular root page here await next(); } });
I updated my answer with what works just fine for me.
ok, I got it working. I had to put that code above the UseStaticFiles statement in my Configure method.

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.