HTML does not load when refreshing the route in ASP .NET with angular

Viewed 313

I have build my angular app and the output is wwwroot folder inside my ASP .NET API folder. When I build the app with dotnet watch run, everything works and shows normally, but when I refresh the route localhost:5000/users, it shows me raw json file instead of HTML/CSS content

Console error shows the following message: Content Security Policy: The page’s settings blocked the loading of a resource at https://localhost:5000/favicon.ico (“default-src”); In network refer-policy says "strict-origin-when-cross-origin" but my cors is set app.UseCors(x=>x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());

My endpoints

app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
               endpoints.MapFallbackToController("Index","Fallback");
            
                
            });

Fallback Controller

 public class FallbackController : Controller
    {
        public IActionResult Index(){

            return PhysicalFile(Path.Combine(Directory.GetCurrentDirectory(),"wwwroot","index.html"),
            "text/HTML");
        }
    }

Index.html from wwwroot folder

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>SocialNetworkSPA</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
  <app-root></app-root>
</body>
</html>

My ASP .NET Core version is 3.1 and Angular 11

Error img http://i.prntscr.com/EX2RFqRrSkS9b2gEESbdLQ.png

Please not that everything is functional and works normally until I refresh the page, then these error occurs

2 Answers

Try this:-

 app.UseCors(x => x.AllowAnyHeader().AllowAnyMethod().WithOrigins("https://localhost:xxxx"));

And don't forget to add services.AddCors(); to your ConfigureServices.

You have a route conflict for the /users path - it gets routed to your API controller instead of being routed to the controller that serves your Angular app.

You have to rethink your ASP.NET route configuration, e.g. make sure all API routes are prefixed by api/ so that there's never a conflict with Angular.

Related