This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Note
Access to this page requires authorization. You can trysigning in orchanging directories.
Access to this page requires authorization. You can trychanging directories.
Note
This isn't the latest version of this article. For the current release, see the.NET 9 version of this article.
Warning
This version of ASP.NET Core is no longer supported. For more information, see the.NET and .NET Core Support Policy. For the current release, see the.NET 9 version of this article.
Important
This information relates to a pre-release product that may be substantially modified before it's commercially released. Microsoft makes no warranties, express or implied, with respect to the information provided here.
For the current release, see the.NET 9 version of this article.
This tutorial teaches the basics of building a real-time app using SignalR. You learn how to:
At the end, you'll have a working chat app:
Visual Studio 2022 with theASP.NET and web development workload.
Start Visual Studio 2022 and selectCreate a new project.
In theCreate a new project dialog, selectASP.NET Core Web App (Razor Pages), and then selectNext.
In theConfigure your new project dialog, enterSignalRChat
forProject name. It's important to name the projectSignalRChat
, including matching the capitalization, so the namespaces match the code in the tutorial.
SelectNext.
In theAdditional information dialog, select.NET 8.0 (Long Term Support) and then selectCreate.
The SignalR server library is included in the ASP.NET Core shared framework. The JavaScript client library isn't automatically included in the project. For this tutorial, use Library Manager (LibMan) to get the client library fromunpkg.unpkg
is a fast, global content delivery network for everything onnpm.
InSolution Explorer, right-click the project, and selectAdd >Client-Side Library.
In theAdd Client-Side Library dialog:
@microsoft/signalr@latest
forLibrary.signalr.js
andsignalr.min.js
.wwwroot/js/signalr/
.LibMan creates awwwroot/js/signalr
folder and copies the selected files to it.
Ahub is a class that serves as a high-level pipeline that handles client-server communication.
In the SignalRChat project folder, create aHubs
folder.
In theHubs
folder, create theChatHub
class with the following code:
using Microsoft.AspNetCore.SignalR;namespace SignalRChat.Hubs{ public class ChatHub : Hub { public async Task SendMessage(string user, string message) { await Clients.All.SendAsync("ReceiveMessage", user, message); } }}
TheChatHub
class inherits from the SignalRHub class. TheHub
class manages connections, groups, and messaging.
TheSendMessage
method can be called by a connected client to send a message to all clients. JavaScript client code that calls the method is shown later in the tutorial. SignalR code is asynchronous to provide maximum scalability.
The SignalR server must be configured to pass SignalR requests to SignalR. Add the following highlighted code to theProgram.cs
file.
using SignalRChat.Hubs;var builder = WebApplication.CreateBuilder(args);// Add services to the container.builder.Services.AddRazorPages();builder.Services.AddSignalR();var app = builder.Build();// Configure the HTTP request pipeline.if (!app.Environment.IsDevelopment()){ 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.UseRouting();app.UseAuthorization();app.MapRazorPages();app.MapHub<ChatHub>("/chatHub");app.Run();
The preceding highlighted code adds SignalR to the ASP.NET Core dependency injection and routing systems.
Replace the content inPages/Index.cshtml
with the following code:
@page<div> <div> <div>User</div> <div><input type="text" /></div> </div> <div> <div>Message</div> <div><input type="text" /></div> </div> <div> <div> <input type="button" value="Send Message" /> </div> </div> <div> <div> <hr /> </div> </div> <div> <div> <ul></ul> </div> </div></div><script src="~/js/signalr/dist/browser/signalr.js"></script><script src="~/js/chat.js"></script>
The preceding markup:
id="messagesList"
for displaying messages that are received from the SignalR hub.chat.js
app code is created in the next step.In thewwwroot/js
folder, create achat.js
file with the following code:
"use strict";var connection = new signalR.HubConnectionBuilder().withUrl("/chatHub").build();//Disable the send button until connection is established.document.getElementById("sendButton").disabled = true;connection.on("ReceiveMessage", function (user, message) { var li = document.createElement("li"); document.getElementById("messagesList").appendChild(li); // We can assign user-supplied strings to an element's textContent because it // is not interpreted as markup. If you're assigning in any other way, you // should be aware of possible script injection concerns. li.textContent = `${user} says ${message}`;});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();});
The preceding #"tablist">
SelectCtrl+F5 to run the app without debugging.
Copy the URL from the address bar, open another browser instance or tab, and paste the URL in the address bar.
Choose either browser, enter a name and message, and select theSend Message button.
The name and message are displayed on both pages instantly.
Tip
If the app doesn't work, open the browser developer tools (F12) and go to the console. Look for possible errors related to HTML and JavaScript code. For example, ifsignalr.js
was put in a different folder than directed, the reference to that file won't work resulting in a 404 error in the console.If an
ERR_SPDY_INADEQUATE_TRANSPORT_SECURITY
error has occurred in Chrome, run the following commands to update the development certificate:
dotnet dev-certs https --cleandotnet dev-certs https --trust
For information on deploying to Azure, seeQuickstart: Deploy an ASP.NET web app. For more information on Azure SignalR Service, seeWhat is Azure SignalR Service?.
This tutorial teaches the basics of building a real-time app using SignalR. You learn how to:
At the end, you'll have a working chat app:
Visual Studio 2022 with theASP.NET and web development workload.
Start Visual Studio 2022 and selectCreate a new project.
In theCreate a new project dialog, selectASP.NET Core Web App, and then selectNext.
In theConfigure your new project dialog, enterSignalRChat
forProject name. It's important to name the projectSignalRChat
, including matching the capitalization, so the namespaces match the code in the tutorial.
SelectNext.
In theAdditional information dialog, select.NET 7.0 (Standard Term Support) and then selectCreate.
The SignalR server library is included in the ASP.NET Core shared framework. The JavaScript client library isn't automatically included in the project. For this tutorial, use Library Manager (LibMan) to get the client library fromunpkg.unpkg
is a fast, global content delivery network for everything onnpm.
InSolution Explorer, right-click the project, and selectAdd >Client-Side Library.
In theAdd Client-Side Library dialog:
@microsoft/signalr@latest
forLibrary.signalr.js
andsignalr.min.js
.wwwroot/js/signalr/
.LibMan creates awwwroot/js/signalr
folder and copies the selected files to it.
Ahub is a class that serves as a high-level pipeline that handles client-server communication.
In the SignalRChat project folder, create aHubs
folder.
In theHubs
folder, create theChatHub
class with the following code:
using Microsoft.AspNetCore.SignalR;namespace SignalRChat.Hubs{ public class ChatHub : Hub { public async Task SendMessage(string user, string message) { await Clients.All.SendAsync("ReceiveMessage", user, message); } }}
TheChatHub
class inherits from the SignalRHub class. TheHub
class manages connections, groups, and messaging.
TheSendMessage
method can be called by a connected client to send a message to all clients. JavaScript client code that calls the method is shown later in the tutorial. SignalR code is asynchronous to provide maximum scalability.
The SignalR server must be configured to pass SignalR requests to SignalR. Add the following highlighted code to theProgram.cs
file.
using SignalRChat.Hubs;var builder = WebApplication.CreateBuilder(args);// Add services to the container.builder.Services.AddRazorPages();builder.Services.AddSignalR();var app = builder.Build();// Configure the HTTP request pipeline.if (!app.Environment.IsDevelopment()){ 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.UseRouting();app.UseAuthorization();app.MapRazorPages();app.MapHub<ChatHub>("/chatHub");app.Run();
The preceding highlighted code adds SignalR to the ASP.NET Core dependency injection and routing systems.
Replace the content inPages/Index.cshtml
with the following code:
@page<div> <div> <div>User</div> <div><input type="text" /></div> </div> <div> <div>Message</div> <div><input type="text" /></div> </div> <div> <div> <input type="button" value="Send Message" /> </div> </div> <div> <div> <hr /> </div> </div> <div> <div> <ul></ul> </div> </div></div><script src="~/js/signalr/dist/browser/signalr.js"></script><script src="~/js/chat.js"></script>
The preceding markup:
id="messagesList"
for displaying messages that are received from the SignalR hub.chat.js
app code is created in the next step.In thewwwroot/js
folder, create achat.js
file with the following code:
"use strict";var connection = new signalR.HubConnectionBuilder().withUrl("/chatHub").build();//Disable the send button until connection is established.document.getElementById("sendButton").disabled = true;connection.on("ReceiveMessage", function (user, message) { var li = document.createElement("li"); document.getElementById("messagesList").appendChild(li); // We can assign user-supplied strings to an element's textContent because it // is not interpreted as markup. If you're assigning in any other way, you // should be aware of possible script injection concerns. li.textContent = `${user} says ${message}`;});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();});
The preceding #"tablist">
SelectCtrl+F5 to run the app without debugging.
Copy the URL from the address bar, open another browser instance or tab, and paste the URL in the address bar.
Choose either browser, enter a name and message, and select theSend Message button.
The name and message are displayed on both pages instantly.
Tip
If the app doesn't work, open the browser developer tools (F12) and go to the console. Look for possible errors related to HTML and JavaScript code. For example, ifsignalr.js
was put in a different folder than directed, the reference to that file won't work resulting in a 404 error in the console.If an
ERR_SPDY_INADEQUATE_TRANSPORT_SECURITY
error has occurred in Chrome, run the following commands to update the development certificate:
dotnet dev-certs https --cleandotnet dev-certs https --trust
For information on deploying to Azure, seeQuickstart: Deploy an ASP.NET web app. For more information on Azure SignalR Service, seeWhat is Azure SignalR Service?.
This tutorial teaches the basics of building a real-time app using SignalR. You learn how to:
At the end, you'll have a working chat app:
Start Visual Studio 2022 and selectCreate a new project.
In theCreate a new project dialog, selectASP.NET Core Web App, and then selectNext.
In theConfigure your new project dialog, enterSignalRChat
forProject name. It's important to name the projectSignalRChat
, including matching the capitalization, so the namespaces match the code in the tutorial.
SelectNext.
In theAdditional information dialog, select.NET 6.0 (Long-term support) and then selectCreate.
The SignalR server library is included in the ASP.NET Core shared framework. The JavaScript client library isn't automatically included in the project. For this tutorial, use Library Manager (LibMan) to get the client library fromunpkg.unpkg
is a fast, global content delivery network for everything onnpm.
InSolution Explorer, right-click the project, and selectAdd >Client-Side Library.
In theAdd Client-Side Library dialog:
@microsoft/signalr@latest
forLibrary.signalr.js
andsignalr.min.js
.wwwroot/js/signalr/
.LibMan creates awwwroot/js/signalr
folder and copies the selected files to it.
Ahub is a class that serves as a high-level pipeline that handles client-server communication.
In the SignalRChat project folder, create aHubs
folder.
In theHubs
folder, create theChatHub
class with the following code:
using Microsoft.AspNetCore.SignalR;namespace SignalRChat.Hubs{ public class ChatHub : Hub { public async Task SendMessage(string user, string message) { await Clients.All.SendAsync("ReceiveMessage", user, message); } }}
TheChatHub
class inherits from the SignalRHub class. TheHub
class manages connections, groups, and messaging.
TheSendMessage
method can be called by a connected client to send a message to all clients. JavaScript client code that calls the method is shown later in the tutorial. SignalR code is asynchronous to provide maximum scalability.
The SignalR server must be configured to pass SignalR requests to SignalR. Add the following highlighted code to theProgram.cs
file.
using SignalRChat.Hubs;var builder = WebApplication.CreateBuilder(args);builder.Services.AddRazorPages();builder.Services.AddSignalR();var app = builder.Build();if (!app.Environment.IsDevelopment()){ app.UseExceptionHandler("/Error"); app.UseHsts();}app.UseHttpsRedirection();app.UseStaticFiles();app.UseRouting();app.UseAuthorization();app.MapRazorPages();app.MapHub<ChatHub>("/chatHub");app.Run();
The preceding highlighted code adds SignalR to the ASP.NET Core dependency injection and routing systems.
Replace the content inPages/Index.cshtml
with the following code:
@page <div> <div> <div>User</div> <div><input type="text" /></div> </div> <div> <div>Message</div> <div><input type="text" /></div> </div> <div> <div> <input type="button" value="Send Message" /> </div> </div> <div> <div> <hr /> </div> </div> <div> <div> <ul></ul> </div> </div> </div><script src="~/js/signalr/dist/browser/signalr.js"></script><script src="~/js/chat.js"></script>
The preceding markup:
id="messagesList"
for displaying messages that are received from the SignalR hub.chat.js
app code is created in the next step.In thewwwroot/js
folder, create achat.js
file with the following code:
"use strict";var connection = new signalR.HubConnectionBuilder().withUrl("/chatHub").build();//Disable the send button until connection is established.document.getElementById("sendButton").disabled = true;connection.on("ReceiveMessage", function (user, message) { var li = document.createElement("li"); document.getElementById("messagesList").appendChild(li); // We can assign user-supplied strings to an element's textContent because it // is not interpreted as markup. If you're assigning in any other way, you // should be aware of possible script injection concerns. li.textContent = `${user} says ${message}`;});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();});
The preceding #"tablist">
Press CTRL+F5 to run the app without debugging.
Copy the URL from the address bar, open another browser instance or tab, and paste the URL in the address bar.
Choose either browser, enter a name and message, and select theSend Message button.
The name and message are displayed on both pages instantly.
Tip
If the app doesn't work, open the browser developer tools (F12) and go to the console. Look for possible errors related to HTML and JavaScript code. For example, ifsignalr.js
was put in a different folder than directed, the reference to that file won't work resulting in a 404 error in the console.If an
ERR_SPDY_INADEQUATE_TRANSPORT_SECURITY
error has occurred in Chrome, run the following commands to update the development certificate:
dotnet dev-certs https --cleandotnet dev-certs https --trust
For information on deploying to Azure, seeQuickstart: Deploy an ASP.NET web app. For more information on Azure SignalR Service, seeWhat is Azure SignalR Service?.
This tutorial teaches the basics of building a real-time app using SignalR. You learn how to:
At the end, you'll have a working chat app:
The SignalR server library is included in the ASP.NET Core 3.1 shared framework. The JavaScript client library isn't automatically included in the project. For this tutorial, you use Library Manager (LibMan) to get the client library fromunpkg. unpkg is a content delivery network (CDN) that can deliver anything found in npm, the Node.js package manager.
@microsoft/signalr@latest
.signalr.js
andsignalr.min.js
.LibMan creates awwwroot/js/signalr folder and copies the selected files to it.
Ahub is a class that serves as a high-level pipeline that handles client-server communication.
ChatHub.cs
file with the following code:using Microsoft.AspNetCore.SignalR;using System.Threading.Tasks;namespace SignalRChat.Hubs{ public class ChatHub : Hub { public async Task SendMessage(string user, string message) { await Clients.All.SendAsync("ReceiveMessage", user, message); } }}
TheChatHub
class inherits from the SignalRHub
class. TheHub
class manages connections, groups, and messaging.
TheSendMessage
method can be called by a connected client to send a message to all clients. JavaScript client code that calls the method is shown later in the tutorial. SignalR code is asynchronous to provide maximum scalability.
The SignalR server must be configured to pass SignalR requests to SignalR.
Add the following highlighted code to theStartup.cs
file.
using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using Microsoft.AspNetCore.Builder;using Microsoft.AspNetCore.Hosting;using Microsoft.AspNetCore.HttpsPolicy;using Microsoft.Extensions.Configuration;using Microsoft.Extensions.DependencyInjection;using Microsoft.Extensions.Hosting;using SignalRChat.Hubs;namespace SignalRChat{ 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.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.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); endpoints.MapHub<ChatHub>("/chatHub"); }); } }}
These changes add SignalR to the ASP.NET Core dependency injection and routing systems.
Replace the content inPages/Index.cshtml
with the following code:
@page <div> <div> <div>User</div> <div><input type="text" /></div> </div> <div> <div>Message</div> <div><input type="text" /></div> </div> <div> <div> <input type="button" value="Send Message" /> </div> </div> <div> <div> <hr /> </div> </div> <div> <div> <ul></ul> </div> </div> </div><script src="~/js/signalr/dist/browser/signalr.js"></script><script src="~/js/chat.js"></script>
The preceding code:
id="messagesList"
for displaying messages that are received from the SignalR hub.chat.js
application code that you create in the next step.In thewwwroot/js folder, create achat.js
file with the following code:
"use strict";var connection = new signalR.HubConnectionBuilder().withUrl("/chatHub").build();//Disable send button until connection is establisheddocument.getElementById("sendButton").disabled = true;connection.on("ReceiveMessage", function (user, message) { var li = document.createElement("li"); document.getElementById("messagesList").appendChild(li); // We can assign user-supplied strings to an element's textContent because it // is not interpreted as markup. If you're assigning in any other way, you // should be aware of possible script injection concerns. li.textContent = `${user} says ${message}`;});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();});
The preceding code:
Tip
If the app doesn't work, open your browser developer tools (F12) and go to the console. You might see errors related to your HTML and JavaScript code. For example, suppose you putsignalr.js
in a different folder than directed. In that case the reference to that file won't work and you'll see a 404 error in the console.
If you get the error ERR_SPDY_INADEQUATE_TRANSPORT_SECURITY in Chrome, run these commands to update your development certificate:
dotnet dev-certs https --cleandotnet dev-certs https --trust
For information on deploying to Azure, seeQuickstart: Deploy an ASP.NET web app.
Was this page helpful?
Was this page helpful?