Home > Back-end >  ASP.NET Core 6, Angular & REST prefix (using Microsoft.AspNetCore.SpaProxy)
ASP.NET Core 6, Angular & REST prefix (using Microsoft.AspNetCore.SpaProxy)

Time:06-06

How do I get an ASP.NET Core 6 Angular app working with a prefix on the API routes?

I create a brand new project using the ASP.NET Core with Angular template. I then make two small changes:

  1. Change the Angular component to use the api/ prefix:

enter image description here

  1. Change the WebApi controller to use the api/ prefix:

enter image description here

The result is a 404:

enter image description here

CodePudding user response:

EXPLANATION:

This behaviour is happening because of the change in ASP.NET Core to have the front-end dev server proxy requests to ASP.NET Core, rather than the other way round (which was the approach in previous versions of ASP.NET Core). In other words, the Angular dev server proxies requests to ASP.NET Core for (eg) API data, whereas in previous ASP.NET versions, IIS Express would have proxied Angular requests to the Angular SPA server.

See: configuring bypass for the SPA proxy server

You can use wildcards like "/api/**"

USEFUL TO KNOW:

As this may be useful for related issues, without the prefix in the proxy.conf.js file, the actual response to the HTTP request is as shown:

SPA proxy response

This is not a response from the ASP.NET Core code; this is the response from Angular - i.e. that request is not passing through the Angular proxy server to IIS Express.

Additionally, it's useful to know that the SPA proxy server gets launched using the Microsoft.AspNetCore.SpaProxy package. I had changed my Program.cs startup code entirely to remove the Angular/SPA logic, but I was still getting the SPA Proxy server on startup, and the same response code from the API route. This is because in the launchsettings.json, there are these references to the SpaProxy package:

launch config of the SPA proxy server

So unless you remove those two references in the launchSettings.json file, the SPA proxy will continue to launch. If you want to completely remove the Spa Proxy, remove these references. Then you can debug what is happening without the SPA Proxy involved, if you need to. However, if you want to continue with the new SPA proxy to ASP.NET Core approach, the proxy.conf.js file seems to be the way forward.

  • Related