dotnet / AspNetCore.Docs

Documentation for ASP.NET Core
https://docs.microsoft.com/aspnet/core
Creative Commons Attribution 4.0 International
12.55k stars 25.31k forks source link

Unable to connect to SignalR hub from some other client apllication #17765

Closed sravanithamatamqualbrain closed 4 years ago

sravanithamatamqualbrain commented 4 years ago

Hi Team,

In the example that you have given is for local SignalHub.

if SignalHub application and client application are in different projects and when signalr application is hosted and when we tried to connect to SignalR hub from client application, i am facing some issues related to cors policy and signalr.map is not loaded. And i am unable to connect to hosted signalR hub.

please provide me a example where i can connected to signalR hub remotely from client apllication.

Thank you Sravani Thamatam

BrennanConroy commented 4 years ago

Read up on CORS in SignalR to resolve CORS issues.

signalr.map is not loaded

What errors are you getting?

sravanithamatamqualbrain commented 4 years ago

Access to XMLHttpRequest at 'http://localhost:57223/negotiate?negotiateVersion=1' from origin 'http://localhost:57606' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

sravanithamatamqualbrain commented 4 years ago

The above error i am getting.

please help me.

BrennanConroy commented 4 years ago

Did you read the doc I linked? It should help you resolve the CORS error.

sravanithamatamqualbrain commented 4 years ago

Yes i read that page. But it couldn't help me.

BrennanConroy commented 4 years ago

Share your code on the server that's setting up CORS

sravanithamatamqualbrain commented 4 years ago

public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(options =>
            options.AddDefaultPolicy(builder => builder
            .WithOrigins("http://localhost:57223/")
            .AllowAnyHeader().AllowAnyMethod()));

    services.AddRazorPages();
        services.AddSignalR();

    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseCors();
        app.UseRouting();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapHub<ChatHub>("/chathub");
            endpoints.MapRazorPages();
        });
    }

}

sravanithamatamqualbrain commented 4 years ago

This is the code that is written in Startup.cs file of SignalR application server.

BrennanConroy commented 4 years ago

Remove the trailing "/" in .WithOrigins("http://localhost:57223/") And add .AllowCredentials() to your CORS options

sravanithamatamqualbrain commented 4 years ago

Sure. I will do that.

sravanithamatamqualbrain commented 4 years ago

Still i am facing the same issue.

sravanithamatamqualbrain commented 4 years ago

services.AddCors(options => options.AddDefaultPolicy(builder => builder .WithOrigins("http://localhost:57223") .AllowAnyHeader().AllowAnyMethod() .AllowCredentials()));

BrennanConroy commented 4 years ago

Place UseCors() above the other middleware

app.UseCors();
app.UseHttpsRedirection();
app.UseStaticFiles();
sravanithamatamqualbrain commented 4 years ago

Okay

sravanithamatamqualbrain commented 4 years ago

public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(options =>
            options.AddDefaultPolicy(builder => builder
            .WithOrigins("http://localhost:57223")
            .AllowAnyHeader()
            .AllowAnyMethod()
            .AllowCredentials()));
       services.AddRazorPages();
        services.AddSignalR();

    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }
        app.UseCors(builder =>
        {
            builder.WithOrigins("http://localhost:57223")
                .AllowAnyHeader()
                .AllowCredentials();
        });
        app.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseRouting();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapHub<ChatHub>("/chathub");
            endpoints.MapRazorPages();
        });
    }
}
sravanithamatamqualbrain commented 4 years ago

Still same issue.

BrennanConroy commented 4 years ago

Why did you change your UseCors method to use the builder? If you're going to do that, then you need to have AllowAnyMethod() or WithMethods("GET", "POST").

sravanithamatamqualbrain commented 4 years ago

@page

 
User
Message
 

    sravanithamatamqualbrain commented 4 years ago

    "use strict";

    var connection = new signalR.HubConnectionBuilder().withUrl("http://localhost:57223").build();

    //Disable send button until connection is established document.getElementById("sendButton").disabled = true;

    connection.on("ReceiveMessage", function (user, message) { var msg = message.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">"); var encodedMsg = user + " says " + msg; var li = document.createElement("li"); li.textContent = encodedMsg; document.getElementById("messagesList").appendChild(li); });

    connection.start().then(function () { document.getElementById("sendButton").disabled = false; }).catch(function (err) { return console.error(err.toString()); });

    document.getElementById("sendButton").addEventListener("click", function (event) { var user = document.getElementById("userInput").value; var message = document.getElementById("messageInput").value; connection.invoke("SendMessage", user, message).catch(function (err) { return console.error(err.toString()); }); event.preventDefault(); });

    sravanithamatamqualbrain commented 4 years ago

    this is client code.

    BrennanConroy commented 4 years ago

    Access to XMLHttpRequest at 'http://localhost:57223/negotiate?negotiateVersion=1' from origin 'http://localhost:57606'

    Ok, here's your issue, the client is at origin "http://localhost:57606", so that's the URL you need to use in WithOrigins(...)

    sravanithamatamqualbrain commented 4 years ago

    Failed to load resource: 57223/negotiate?negotiateVersion=1:1 responded with a status of 404 (Not Found)

    sravanithamatamqualbrain commented 4 years ago

    Now this issue is coming.

    BrennanConroy commented 4 years ago

    Your client needs to be pointing at the hub which is at "/chathub" So: var connection = new signalR.HubConnectionBuilder().withUrl("http://localhost:57223/chathub").build();

    sravanithamatamqualbrain commented 4 years ago
    Error
    sravanithamatamqualbrain commented 4 years ago

    Issue is resolved.

    Thank you thank you very much @BrennanConroy.