Angular , CORS and .NET Core SignalR

I have written a .NET Core  SignalR + Agular Observable of continously delivering the data. (http://msprogrammer.serviciipeweb.ro/2018/06/25/net-core-signalr-hub-angular-observable/ )

The setup is that .NET WebAPI resides in Visual Studio Project ( .sln. .csproj) and Angular Project is separate in another folder.

There are some settings in the development to be done in order to work

  1. Setting CORS in .NET Core  ( not really necessary- see below)
  2. Usually you will not need to set CORS in .NET Core if you plan to deliver Angular and .NET Core in the same site.

    But anyway, to allow anyoneto call you API , you will do something like this :

    services.AddCors();
    services.AddMvc();
    //...
     app.UseCors(it =>it.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
    //if (env.IsDevelopment())
    //{
    //    app.UseDeveloperExceptionPage();
    //}
    
    

    Of course, you can set for a domain, a header , and so on

    Also , do not forget to handle CORS errors – either by commenting the developer exception page, either by using a custom middleware, like https://blog.jonathaneckman.io/handling-net-core-web-api-exceptions-with-an-aurelia-fetch-interceptor/

  3. Setting  CORS like it does not exists for Angular
  4. For this:

    In the Angular environment.ts put those:

    export const environment = {

    production: false, //put also in the prod

    urlAPI:’/’

    }

    • In production: deliver AOT Angular compiled in the same folder with the .NET
    • This will ensure that , when you send the Angular AOT build with .NET Core WebAPI in the same site, it will work. NO CORS involved 😉

    • In development: This mean Angular ng server intercepting  calls

    Then create a file named proxy.conf.js and put this to redirect:

    const PROXY_CONFIG = [
        {
          context: [
              "/employees",
              "/api",                
          ],
          target: "http://<url to the .NET Core API>/",
          secure: false,
          "changeOrigin": true,
          "logLevel": "debug",
          ws: true
        }
    ]
    module.exports = PROXY_CONFIG;
    
    

    Then run:

    ng serve –proxy-config proxy.conf.js –open

  • Setting SignalR for Angular in development
  • See ws: true in previous proxy.conf.js ? That is all, if you run

    ng serve –proxy-config proxy.conf.js –open