当前位置:网站首页>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 :

边栏推荐
- Create a new MySQL database under Linux and import SQL files
- [matlab] 2D drawing summary
- Oracle中的With As 子查询
- 终于看懂科学了!200张图领略人类智慧的巅峰
- Imitating freecodecamp to build a programming ability test platform
- [sub matrix quantity statistics] cf1181c flag sub matrix quantity statistics
- Practical cases of data visualization (timeline rotation diagram, streamlit control year metabase visualization tutorial) 2.0
- 数数据可视化实战案例(timeline轮播图,streamlit 控件年份 metabase可视化使用教程)2.0
- return statement
- Policy Center-User Data
猜你喜欢

【时序数据库InfluxDB】Windows环境下配置InfluxDB+数据可视化,以及使用 C#进行简单操作的代码实例

Technology sharing | anyrtc service single port design

Create a new MySQL database under Linux and import SQL files

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

Kubernetes: a comprehensive analysis of container choreography

J - Borg maze (minimum spanning tree +bfs)

比亚迪越来越像华为?

4.2 escape characters

Management joint examination - mathematical formula

Compare whether the two arrays are the same
随机推荐
Complement (Niuke)
Openresty built in variable
1149 dangerous goods packaging (25 points)
4.1 print function
The short video and live broadcast incubation training camp with goods opens nationwide enrollment!
Policy Center > Deceptive Behavior
N - Is There A Second Way Left? (minimum spanning tree, Kruskal)
1058 a+b in Hogwarts (20 points)
Developer practice - the future of Agora home AI audio and video
Preliminary study on AI noise reduction evaluation system of sound network
How to do a good job in high concurrency system design? I have summarized three points
LeCun指明下一代AI方向:自主机器智能
消息队列十连问
topic: Privacy, Deception and Device Abuse
[sub matrix quantity statistics] cf1181c flag sub matrix quantity statistics
K - rochambau (joint search, enumeration)
M - smooth engineering continuation (minimum spanning tree)
Is Domain Driven Design (DDD) reliable?
【时序数据库InfluxDB】Windows环境下配置InfluxDB+数据可视化,以及使用 C#进行简单操作的代码实例
Kindle down, ireader relay