当前位置:网站首页>ASP. Net core signalr tutorial
ASP. Net core signalr tutorial
2022-06-30 15:41:00 【zhoubangbang1】
This tutorial introduces the use of SignalR The basics of generating real-time applications . You will learn :
1. establish Web project .
2. add to SignalR Client library .
3. establish SignalR center .
4. Configure items to use SignalR.
5. Add code to send messages from any client to all connected clients .
Last , You will have a work chat app :
establish Web project
1. Select from the menu “ file ”>“ New projects ” .
2. stay “ New projects ” In the dialog box , choice “ already installed ”>“Visual C#”>“Web”>“ASP.NET Core Web application ” . Name the project “SignalRChat” .

3. choice “Web application ”, To create and use Razor Pages Project .
4. choice “.NET Core” The target framework , choice “ASP.NET Core 2.1”, And then click “ determine ” .

add to SignalR Client library
Microsoft.AspNetCore.App The meta package includes SignalR Server Library . JavaScript Client libraries are not automatically included in the project . For this tutorial , Using the library manager (LibMan) from unpkg Get the client library . unpkg It's a content distribution network (CDN), Can be distributed in npm( namely Node.js Package manager ) Anything found in .
- stay “ Solution explorer ” in , Right click on the item , And then choose “ add to ” >“ Client library ” .

2. stay “ Add Client Library ” In the dialog box , about “ Provider ” , choice “unpkg” .
3. about “ library ” , Input @aspnet/[email protected], Then select the latest version that is not a preview version .
4. choice “ Select a specific file ” , an “dist/browser” Folder , And then choose “signalr.js” and “signalr.min.js” .
5. take “ Target location ” Set to wwwroot/lib/signalr/ , And then choose “ install ” .
establish SignalR center
The center is a class , Used as a processing client - Advanced pipeline for server communication .
? stay SignalRChat In the project folder , establish Hubs Folder .
? stay Hubs In the folder , Use the following code to create ChatHub.cs file :
ChatHub Class inherits from SignalR Hub. Hub Class management connection 、 Groups and messages .
Can be called from a connected client SendMessage, To send messages to all clients . Later in this tutorial, you will see how to invoke this method JavaScript Client code . SignalR The code is asynchronous , Provides maximum scalability .
namespace SignalRChatTest.Hubs
{
public class ChatHub : Hub
{
public async Task SendMessage(string user, string message)
{
await Clients.All.SendAsync("ReceiveMessage", user, message);
}
}
} To configure SignalR
Must be SignalR The server is configured to SignalR Request passed to SignalR.
1. Add the following highlighted code to Startup.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.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using SignalRChatTest.Hubs;
namespace SignalRChatTest
{
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.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddSignalR();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseSignalR(routes =>
{
routes.MapHub<ChatHub>("/chatHub");
});
app.UseMvc();
}
}
}
add to SignalR Client code
@*@page
@model IndexModel
@{
ViewData["Title"] = "Home page";
}
<div id="myCarousel" class="carousel slide" data-ride="carousel" data-interval="6000">
<ol class="carousel-indicators">
<li data-target="#myCarousel" data-slide-to="0" class="active"></li>
<li data-target="#myCarousel" data-slide-to="1"></li>
<li data-target="#myCarousel" data-slide-to="2"></li>
</ol>
<div class="carousel-inner" role="listbox">
<div class="item active">
<img src="~/images/banner1.svg" alt="ASP.NET" class="img-responsive" />
<div class="carousel-caption" role="option">
<p>
Learn how to build ASP.NET apps that can run anywhere.
<a class="btn btn-default" href="https://go.microsoft.com/fwlink/?LinkID=525028&clcid=0x409">
Learn More
</a>
</p>
</div>
</div>
<div class="item">
<img src="~/images/banner2.svg" alt="Visual Studio" class="img-responsive" />
<div class="carousel-caption" role="option">
<p>
There are powerful new features in Visual Studio for building modern web apps.
<a class="btn btn-default" href="https://go.microsoft.com/fwlink/?LinkID=525030&clcid=0x409">
Learn More
</a>
</p>
</div>
</div>
<div class="item">
<img src="~/images/banner3.svg" alt="Microsoft Azure" class="img-responsive" />
<div class="carousel-caption" role="option">
<p>
Learn how Microsoft's Azure cloud platform allows you to build, deploy, and scale web apps.
<a class="btn btn-default" href="https://go.microsoft.com/fwlink/?LinkID=525027&clcid=0x409">
Learn More
</a>
</p>
</div>
</div>
</div>
<a class="left carousel-control" href="#myCarousel" role="button" data-slide="prev">
<span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="right carousel-control" href="#myCarousel" role="button" data-slide="next">
<span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>
<div class="row">
<div class="col-md-3">
<h2>Application uses</h2>
<ul>
<li>Sample pages using ASP.NET Core Razor Pages</li>
<li>Theming using <a href="https://go.microsoft.com/fwlink/?LinkID=398939">Bootstrap</a></li>
</ul>
</div>
<div class="col-md-3">
<h2>How to</h2>
<ul>
<li><a href="https://go.microsoft.com/fwlink/?linkid=852130">Working with Razor Pages.</a></li>
<li><a href="https://go.microsoft.com/fwlink/?LinkId=699315">Manage User Secrets using Secret Manager.</a></li>
<li><a href="https://go.microsoft.com/fwlink/?LinkId=699316">Use logging to log a message.</a></li>
<li><a href="https://go.microsoft.com/fwlink/?LinkId=699317">Add packages using NuGet.</a></li>
<li><a href="https://go.microsoft.com/fwlink/?LinkId=699319">Target development, staging or production environment.</a></li>
</ul>
</div>
<div class="col-md-3">
<h2>Overview</h2>
<ul>
<li><a href="https://go.microsoft.com/fwlink/?LinkId=518008">Conceptual overview of what is ASP.NET Core</a></li>
<li><a href="https://go.microsoft.com/fwlink/?LinkId=699320">Fundamentals of ASP.NET Core such as Startup and middleware.</a></li>
<li><a href="https://go.microsoft.com/fwlink/?LinkId=398602">Working with Data</a></li>
<li><a href="https://go.microsoft.com/fwlink/?LinkId=398603">Security</a></li>
<li><a href="https://go.microsoft.com/fwlink/?LinkID=699321">Client side development</a></li>
<li><a href="https://go.microsoft.com/fwlink/?LinkID=699322">Develop on different platforms</a></li>
<li><a href="https://go.microsoft.com/fwlink/?LinkID=699323">Read more on the documentation site</a></li>
</ul>
</div>
<div class="col-md-3">
<h2>Run & Deploy</h2>
<ul>
<li><a href="https://go.microsoft.com/fwlink/?LinkID=517851">Run your app</a></li>
<li><a href="https://go.microsoft.com/fwlink/?LinkID=517853">Run tools such as EF migrations and more</a></li>
<li><a href="https://go.microsoft.com/fwlink/?LinkID=398609">Publish to Microsoft Azure App Service</a></li>
</ul>
</div>
</div>*@
@page
<div class="container">
<div class="row"> </div>
<div class="row">
<div class="col-6"> </div>
<div class="col-6">
User..........<input type="text" id="userInput" />
<br />
Message...<input type="text" id="messageInput" />
<input type="button" id="sendButton" value="Send Message" />
</div>
</div>
<div class="row">
<div class="col-12">
<hr />
</div>
</div>
<div class="row">
<div class="col-6"> </div>
<div class="col-6">
<ul id="messagesList"></ul>
</div>
</div>
</div>
<script src="~/lib/signalr/dist/browser/signalr.js"></script>
<script src="~/js/chat.js"></script>stay wwwroot/js In the folder , Use the following code to create chat.js file :
"use strict";
var connection = new signalR.HubConnectionBuilder().withUrl("/chatHub").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();
});Run the application
1. Copy... From the address bar URL, Open another browser instance or tab , And paste this in the address bar URL.
2. Select any browser , Enter a name and message , And then choose “ Send a message ” Button .
3. The name and message are immediately displayed on both pages

Please pay attention to my WeChat official account , Let's make progress together :

边栏推荐
- 1077 kuchiguse (20 points)
- O - ACM contest and blackout (minimum spanning tree, Kruskal)
- At the beginning of the 2022 new year, I will send you hundreds of dry articles
- Technology sharing | how to quickly realize audio and video online calls
- C. Registration system(map)
- Help you accumulate audio and video knowledge, Agora developer's roaming guide officially set sail
- topic: Privacy, Deception and Device Abuse
- L - Jungle roads (minimum spanning tree)
- Basic literacy - four common software architectures
- 数据治理市场:亿信华辰朝左,华傲数据向右
猜你喜欢

数据治理市场:亿信华辰朝左,华傲数据向右

Scattered knowledge of C language (unfinished)

Single cycle CPU of the design group of West University of Technology

4.3 variables and assignments

爬虫(1) - 爬虫基础入门理论篇

开源 STM32 USB-CAN项目

《你的灯亮着吗》开始解决问题前,得先知道“真问题”是什么

Talk about why I started technical writing

J - Borg maze (minimum spanning tree +bfs)

Model system: Sword (1)
随机推荐
开源 STM32 USB-CAN项目
Policy Center-Permissions and APIs that Access Sensitive Information
Message queue ten questions
The crystal ball "data insight" was officially launched: insight into the change of consumption trend and the details of interactive experience
1062 talent and virtue (25 points)
Fundamentals of C language -- similarities and differences between arrays and pointers
Noj1042 - electronic mouse running through maze
H - Arctic network (minimum spanning tree)
openresty 内置变量
【时序数据库InfluxDB】Windows环境下配置InfluxDB+数据可视化,以及使用 C#进行简单操作的代码实例
With as subquery in Oracle
The short video and live broadcast incubation training camp with goods opens nationwide enrollment!
Start your global dynamic acceleration journey of Web services in three steps
Kubernetes: a comprehensive analysis of container choreography
交调与互调的区别
Kindle down, ireader relay
Compare whether the two arrays are the same
ADB devices cannot detect the problem of Xiaomi note 3
剑指 Offer II 080. 含有 k 个元素的组合 回溯
FoxPro and I