ASP.NET Core SignalR 入门教程

本教程介绍使用 SignalR 生成实时应用的基础知识。 您将学习:
1.    创建 Web 项目。
2.    添加 SignalR 客户端库。
3.    创建 SignalR 中心。
4.    配置项目以使用 SignalR。
5.    添加可将消息从任何客户端发送到所有连接客户端的代码。
最后,你将拥有一个工作聊天应用:

创建 Web 项目

1.从菜单中选择“文件”>“新建项目” 。

2.在“新建项目”对话框中,选择“已安装”>“Visual C#”>“Web”>“ASP.NET Core Web 应用” 。 将项目命名为“SignalRChat” 。

watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3pob3ViYW5nYmFuZzE=,size_16,color_FFFFFF,t_70

 

3.选择“Web 应用”,以创建使用 Razor Pages 的项目 。

4. 选择“.NET Core”目标框架,选择“ASP.NET Core 2.1”,然后单击“确定” 。

watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3pob3ViYW5nYmFuZzE=,size_16,color_FFFFFF,t_70

添加 SignalR 客户端库

Microsoft.AspNetCore.App 元包中包括 SignalR 服务器库。 JavaScript 客户端库不会自动包含在项目中。 对于此教程,使用库管理器 (LibMan) 从 unpkg 获取客户端库。 unpkg 是一个内容分发网络 (CDN),可以分发在 npm(即 Node.js 包管理器)中找到的任何内容。

  1. 在“解决方案资源管理器” 中,右键单击项目,然后选择“添加” >“客户端库” 。

watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3pob3ViYW5nYmFuZzE=,size_16,color_FFFFFF,t_70

2.    在“添加客户端库” 对话框中,对于“提供程序” ,选择“unpkg” 。
3.    对于“库” ,输入 @aspnet/signalr@1,然后选择不是预览版的最新版本。
4.    选择“选择特定文件” ,展开“dist/browser” 文件夹,然后选择“signalr.js” 和“signalr.min.js” 。
5.    将“目标位置” 设置为 wwwroot/lib/signalr/ ,然后选择“安装” 。
watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3pob3ViYW5nYmFuZzE=,size_16,color_FFFFFF,t_70

创建 SignalR 中心
中心是一个类,用作处理客户端 - 服务器通信的高级管道。
?    在 SignalRChat 项目文件夹中,创建 Hubs 文件夹 。
?    在 Hubs 文件夹中,使用以下代码创建 ChatHub.cs 文件 :
ChatHub 类继承自 SignalR Hub。 Hub 类管理连接、组和消息。
可通过已连接客户端调用 SendMessage,以向所有客户端发送消息。 本教程后面部分将显示调用该方法的 JavaScript 客户端代码。 SignalR 代码是异步模式,可提供最大的可伸缩性。
 

namespace SignalRChatTest.Hubs
{
    public class ChatHub : Hub
    {
        public async Task SendMessage(string user, string message)
        {
            await Clients.All.SendAsync("ReceiveMessage", user, message);
        }
    }
}

配置 SignalR
必须将 SignalR 服务器配置为将 SignalR 请求传递给 SignalR。
 1. 将以下突出显示的代码添加到 Startup.cs 文件 
 

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();
        }
    }
}

添加 SignalR 客户端代码

@*@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 &amp; 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">&nbsp;</div>
    <div class="row">
        <div class="col-6">&nbsp;</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">&nbsp;</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>

在 wwwroot/js 文件夹中,使用以下代码创建 chat.js 文件 :

"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, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
    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();
});

运行应用

1.从地址栏复制 URL,打开另一个浏览器实例或选项卡,并在地址栏中粘贴该 URL。

2.选择任一浏览器,输入名称和消息,然后选择“发送消息”按钮 。

3.两个页面上立即显示名称和消息

watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3pob3ViYW5nYmFuZzE=,size_16,color_FFFFFF,t_70

请关注我的微信公众号,我们一起进步:

watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3pob3ViYW5nYmFuZzE=,size_16,color_FFFFFF,t_70

  1.  

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值