Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ConnectionId Required when navigating to SignalR page #31

Closed
alexanderjwoods opened this issue Jun 5, 2019 · 1 comment
Closed

ConnectionId Required when navigating to SignalR page #31

alexanderjwoods opened this issue Jun 5, 2019 · 1 comment

Comments

@alexanderjwoods
Copy link

Startup from Server:
[code]
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.ResponseCompression;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Newtonsoft.Json.Serialization;
using System.Linq;

namespace BlazorAndSignalR.Server
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().AddNewtonsoftJson();
services.AddResponseCompression(opts =>
{
opts.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(
new[] { "application/octet-stream" });
});

        services.AddCors(options => options.AddPolicy("CorsPolicy", builder =>
        {
            builder.AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials()
                .WithOrigins("http://localhost:51742");
        }));
        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)
    {
        app.UseResponseCompression();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseBlazorDebugging();
        }

        app.UseRouting();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapDefaultControllerRoute();
        });

        app.UseCors("CorsPolicy");
        app.UseSignalR(routes => routes.MapHub<ChatHub>("/chathub"));
        app.UseHttpsRedirection();
        app.UseBlazor<Client.Startup>();
    }
}

}

[/code]

Hub:
[code]
using Microsoft.AspNetCore.SignalR;
using System.Threading.Tasks;

namespace BlazorAndSignalR.Server
{
public class ChatHub : Hub
{
public override Task OnConnectedAsync()
{
if(string.IsNullOrEmpty(Context.ConnectionId))
{
throw new System.Exception(nameof(Context.ConnectionId)); //This code is never hit
}
Clients.All.SendAsync("broadcastMessage", "system", $"{Context.ConnectionId} joined the conversation");
return base.OnConnectedAsync();
}
public void Send(string name, string message)
{
Clients.All.SendAsync("broadcastMessage", name, message);
}

    public override Task OnDisconnectedAsync(System.Exception exception)
    {
        Clients.All.SendAsync("broadcastMessage", "system", $"{Context.ConnectionId} left the conversation");
        return base.OnDisconnectedAsync(exception);
    }
}

}
[/code]

Page:
[code]
@page "/chathub"

@functions { [Inject] IJSRuntime jsRuntime { get; set; }
HubConnection connection;
string Message = "";
IList<string> messages = new List<string>();

protected override async Task OnInitAsync()
{
    connection = new HubConnectionBuilder(jsRuntime).WithUrl("https://localhost:51742/chathub").Build();
    connection.On<string, string>("broadcastMessage", this.OnBroadcastMessage);
    await connection.StartAsync();
}

Task OnBroadcastMessage(string name, string message)
{
    messages.Add(name + " : " + message);
    StateHasChanged();
    return Task.CompletedTask;
}

async Task SendMessage()
{
    await connection.InvokeAsync("Send", "Blazor Client", Message);
    Message = "";
}

}
[/code]

@galvesribeiro
Copy link
Member

The preview7 package was published. Please try it out.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants