简体   繁体   中英

How to configure Angular 6 URL rewrite in dotnet core using IIS appsettings.json

I'm deploying an Angular SPA to my .NET Core app using IIS.

I do a production Angular build (ng build --base-href /ng --deploy-url /ng) and deploy it to wwwroot in the ng directory.

I currently have it working when you manually go to the Angular url for index.html:

https://localhost:44316/ng/index.html

However, if you refresh or manually navigate to a url, you get a 404.

https://localhost:44316/ng/dash

Not surprising, given that Angular says this will happen without a URL redirect. In the Angular documentation , it says to insert a rewrite rule into web.config.

However, I'm using .NET Core, and one of my team members has informed me that modifying the web.config XML is the old way of doing things. It looks like I need to modify appsettings.json to make this rewrite rule happen.

Soo....Anyone done this before? If I don't modify web.config to set up my forward, how do I set it up?

Have you tried using hash strategy to confirm that this may be a server misconfiguration? Usually 404 happens when the server is not pointing to the "main angular's page", which is the index.html you mentioned.

To use hash strategy you just need to add this parameter to your RouterModule import:

RouterModule.forRoot(routes, {useHash: true})

I forget where I found this little code snippet, but it did the trick. I used the following in Configure() in Startup.cs:

        app.Run(async (context) =>
       {
           context.Response.ContentType = "text/html";
           await context.Response.SendFileAsync(Path.Combine(env.WebRootPath, "ng/index.html"));
       });

Basically, on all the pages in my ng directory, it will load up index.html (without changing the url).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM