Unable to start a connection to signalr core hub with Angular 5 client

pieperu picture pieperu · Jan 5, 2018 · Viewed 10.5k times · Source

I have a .Net Core 2.0 C# Web Api running a SignalR Core hub. I am unable to even start() my hubConnection from angular (5.0.1) receiving this error:

OPTIONS https://localhost:44301/hubs/sample 405 (Method Not Allowed)

Error: Failed to start the connection. Error: Method Not Allowed

Error while establishing connection :(

XHR failed loading: OPTIONS "https://localhost:44301/hubs/sample".

HttpError: Method Not Allowed at XMLHttpRequest.xhr.onload [as __zone_symbol__ON_PROPERTYload] (webpack-internal:///../../../../@aspnet/signalr-client/dist/src/HttpClient.js:30:28) at XMLHttpRequest.wrapFn (webpack-internal:///../../../../zone.js/dist/zone.js:1166:39) at ZoneDelegate.invokeTask (webpack-internal:///../../../../zone.js/dist/zone.js:425:31) at Object.onInvokeTask (webpack-internal:///../../../core/esm5/core.js:4816:33) at ZoneDelegate.invokeTask (webpack-internal:///../../../../zone.js/dist/zone.js:424:36) at Zone.runTask (webpack-internal:///../../../../zone.js/dist/zone.js:192:47) at ZoneTask.invokeTask [as invoke] (webpack-internal:///../../../../zone.js/dist/zone.js:499:34) at invokeTask (webpack-internal:///../../../../zone.js/dist/zone.js:1540:14) at XMLHttpRequest.globalZoneAwareCallback (webpack-internal:///../../../../zone.js/dist/zone.js:1566:17)

I am struggling to even debug this problem, even with the help of fiddler i'm not able to solve it. It does not appear to be a problem with my Api because the Kestrel console prints that the request to the hub came in, but does not print any error. And I am able to GET, PUT and POST to my controllers without issue.

Here is my StartUp.cs configuration (I have omitted code not relevant for brevity)

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
    {
        options.AddPolicy(
            "CorsPolicy",
            builder =>
                builder
                .AllowAnyOrigin()
                .AllowAnyHeader()
                .AllowAnyMethod()
                .AllowCredentials()
        );
    });

    services.AddAuthentication();
    services.AddMvcCore()
        .AddAuthorization(options => {...});
    services.AddAuthentication("Bearer")
        .AddIdentityServerAuthentication(options => {...});

    services.AddSignalR();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseCors("CorsPolicy");
    app.UseAuthentication();

    app.UseSignalR(routes =>
    {
        routes.MapHub<SampleHub>("/hubs/sample");
    });

    app.UseMvc();
}

Here is my sample hub

public interface ISampleHubClient 
{
    Task receiveMessage(SampleRequest msg);
}

public class SampleHub : Hub<ISampleHubClient>
{
    private static string _connectionId;

    public async Task Subscribe(string groupName)
    {
        await Groups.AddAsync(Context.ConnectionId, groupName);

        await Clients.Client(Context.ConnectionId).receiveMessage("Subscribed to " + groupName);
    }

    /// <inheritdoc />
    public Task Send(SampleRequest msg)
    {
        ConsoleColor.Green.WriteLine("Send : " + _connectionId);

        return Clients.Group(msg.Group).receiveMessage(msg);
    }
}

And here is my Angular component code:

import { HubConnection } from '@aspnet/signalr-client';

@Component({})
export class SignalRTestComponent implements OnInit {
    private hubConnection: HubConnection;

    ngOnInit() {
        this.initHub();
    }

    initHub()
    {
        let self = this;
        var signalrBaseUri = "https://localhost:44301/hubs/sample";

       this.hubConnection = new HubConnection(signalrBaseUri);

        this.hubConnection
        .start() // <- Failure here
        .then(() =>{
             self.hubConnection.invoke("Subscribe", this.groupName);
        })
        .catch(err => { console.log("INVOKE FAILED");console.error(err);});             
    })
    .catch(err => 
    {
        console.log('Error while establishing connection :(');
        console.log(err);
    });

    this.hubConnection.on('receiveMessage', (receivedMessage: SampleMessage) => {
        console.log("Message received : ");
        console.log(sampleMessage);
    });
}
}

Any help would be greatly appreciated

Answer

Thomas picture Thomas · Mar 15, 2018

The issue is, that the npm package has been renamed from @aspnet/signalr-client to @aspnet/signalr. Changing to this the new package and also fixing the imports worked for me (to at least get rid of the OPTIONS call error.

import { HubConnection } from '@aspnet/signalr'