ponna

ponna

  • NA
  • 20
  • 0

Angular 8 with Signal R and Web API

May 8 2020 12:24 AM
Hi Everyone,
 
We are trying to implement Signalr with Web API in Angular 8. The below are the code which we have implmented
 
Angular 8:
  1. this._hubConnection = new signalR.HubConnectionBuilder()  
  2. .withUrl('http://localhost:50633/MessageHub')  
  3. .build();  
  4. }  
  5. private startConnection(): void {  
  6. this._hubConnection  
  7. .start()  
  8. .then(() => {  
  9. this.connectionIsEstablished = true;  
  10. console.log('Hub connection started');  
  11. this.connectionEstablished.emit(true);  
  12. })  
  13. .catch(err => {  
  14. console.log('Error while establishing connection, retrying...');  
  15. setTimeout(function () { this.startConnection(); }, 5000);  
  16. });  
  17. }  
Web API code:
 
Web API Config: 
  1. public static void Register(HttpConfiguration config)  
  2. {  
  3. // New code  
  4. //config.EnableCors();  
  5. var cors = new EnableCorsAttribute("*""*""*");  
  6. config.EnableCors(cors);  
  7. config.Routes.MapHttpRoute(  
  8. name: "DefaultApi",  
  9. routeTemplate: "api/{controller}/{id}",  
  10. defaults: new { id = RouteParameter.Optional }  
  11. );  
  12. }  
Start Up file:
  1. app.Map("/signalr", map =>  
  2. {  
  3. // Setup the CORS middleware to run before SignalR.  
  4. // By default this will allow all origins. You can  
  5. // configure the set of origins and/or http verbs by  
  6. // providing a cors options with a different policy.  
  7. //map.UseCors(CorsOptions.AllowAll);  
  8. var hubConfiguration = new HubConfiguration  
  9. {  
  10. // You can enable JSONP by uncommenting line below.  
  11. // JSONP requests are insecure but some older browsers (and some  
  12. // versions of IE) require JSONP to work cross domain  
  13. EnableJSONP = true,  
  14. EnableJavaScriptProxies = true,  
  15. EnableDetailedErrors = true  
  16. };  
  17. // Run the SignalR pipeline. We're not using MapSignalR  
  18. // since this branch already runs under the "/signalr"  
  19. // path.  
  20. map.RunSignalR(hubConfiguration);  
  21. });  
  22. app.MapSignalR();  
We are facing issue unable to establish a hubconnection. Can any one help to resolve the below issue.
Access to XMLHttpRequest at 'http://localhost:50633/MessageHub/negotiate' from origin 'http://localhost:4200' has been blocked by CORS policy: Request header field x-requested-with is not allowed by Access-Control-Allow-Headers in preflight response.
 
Thanks,
Venkatesh.P

Answers (1)