当前位置:网站首页>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 :
边栏推荐
- Start your global dynamic acceleration journey of Web services in three steps
- openresty 内置变量
- Go-Micro安装
- Web technology sharing | whiteboard toolbar encapsulation of Web
- Explain service idempotency design in detail
- RTC monthly tabloid programming challenge ended successfully in June; Review of the first anniversary of sound network's listing
- 阿里云oss对象存储跨域设置
- (Niuke) BFS
- ADB devices cannot detect the problem of Xiaomi note 3
- BYD is more and more like Huawei?
猜你喜欢
Preliminary study on AI noise reduction evaluation system of sound network
Complement (Niuke)
Zero basic C language learning notes -- first introduction -- 2 data types & variables and constants
Policy Center-User Data
Teach you a learning method to quickly master knowledge
Advanced C language - pointer 3 - knowledge points sorting
[sub matrix quantity statistics] cf1181c flag sub matrix quantity statistics
Experiment of the planning group of the West University of technology -- pipeline CPU and data processing Adventure
topic: Privacy, Deception and Device Abuse
阿里云oss对象存储跨域设置
随机推荐
深入理解.Net中的线程同步之构造模式(二)内核模式1.内核模式构造物Event事件
【时序数据库InfluxDB】Windows环境下配置InfluxDB+数据可视化,以及使用 C#进行简单操作的代码实例
【Leetcode】链表排序(逐步提高时空复杂度)
Kindle down, ireader relay
The short video and live broadcast incubation training camp with goods opens nationwide enrollment!
1015 reversible primes (20 points)
openresty 内置变量
Rte2021 review of the practice and the way of AI OPS landing
Imeta | Ye Mao / Shi Yu reviewed the dynamic shuttle and ecological function of intracellular and extracellular genes in the environmental microbiome
Experiment of the planning group of the West University of technology -- pipeline CPU and data processing Adventure
交调与互调的区别
Oculus quest2 | unity configures the oculus quest2 development environment and packages an application for real machine testing
FoxPro and I
4.2 escape characters
Alibaba cloud OSS object storage cross domain settings
Policy Center-Permissions and APIs that Access Sensitive Information
Teach you a learning method to quickly master knowledge
Flask Sqlalchemy - how to use custom query criteria ---orm (7)
Policy Center > Deceptive Behavior
Openresty built in variable