[SignalR] - 由 WebAPI 服務向 Web 頁面主動實時推送消息


框架

后端服務:.Net Core 3.1 WebAPI
前端頁面:.Net Core 3.1 MVC

 

服務端

1. 跨域配置(CORS

使用 Nuget 安裝 Microsoft.AspNet.WebApi.Cors

2. 項目配置(Startup)

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.AddControllers();
        services.AddSignalR();
        services.AddCors(op => { op.AddPolicy("cors", set => { set.SetIsOriginAllowed(origin => true).AllowAnyHeader().AllowAnyMethod().AllowCredentials(); }); });
    }

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

        app.UseCors("cors");
        app.UseRouting();
        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
            endpoints.MapHub<NotificationHub>("/NotificationHub");
        });
    }
}

3. 業務邏輯,主動推送消息

[ApiController]
[Route("[controller]")]
public class NotificationController : ControllerBase
{
	private readonly ILogger<NotificationController> _logger;
	private readonly IHubContext<NotificationHub> _hubContext;

	public NotificationController(ILogger<NotificationController> logger, IHubContext<NotificationHub> hubContext)
	{
		_logger = logger;
		_hubContext = hubContext;
	}

	[HttpGet]
	public string Get()
	{
		var message = new NotificationModel { Gid = Guid.NewGuid() };
		var json = Newtonsoft.Json.JsonConvert.SerializeObject(message);
		//_hubContext.Clients.All.SendAsync("NotificationCenter", json);
		_hubContext.Clients.Group("5f3b332bbdae582770fb5ec9").SendAsync("NotificationCenter", json);
		return Convert.ToString(json);
	}
}

public class NotificationModel
{
	public Guid Gid { get; set; }
}

 

客戶端配置

1. 為解決方案添加 SignalR 客戶端庫

2. 業務邏輯,接收推送過來的消息

"use strict";

var connection = new signalR.HubConnectionBuilder().withUrl("http://localhost:7370/NotificationHub").build();

connection.start().then(function () {
    var groupId = "5f3b332bbdae582770fb5ec9";
    connection.invoke("AddToGroup", groupId);
}).catch(function (err) {
    return console.error(err.toString());
});

connection.on("NotificationCenter", function (json) {
    var _obj = JSON.parse(json);
    var _div = document.createElement('div');
    _div.innerText = _obj.Gid;
    document.getElementById("messagesList").appendChild(_div);
});

 

范例演示

 

指定推送對象

所有連接的客戶。
Clients.All.addContosoChatMessageToPage(name, message);

只有呼叫客戶端。
Clients.Caller.addContosoChatMessageToPage(name, message);

除呼叫客戶端外的所有客戶端。
Clients.Others.addContosoChatMessageToPage(name, message);

由連接ID標識的特定客戶端。
Clients.Client(Context.ConnectionId).addContosoChatMessageToPage(name, message);

除了指定的客戶端的所有連接的客戶端,由連接ID標識。
Clients.AllExcept(connectionId1, connectionId2).addContosoChatMessageToPage(name, message);

在指定的組中的所有連接的客戶端。
Clients.Group(groupName).addContosoChatMessageToPage(name, message);

指定組中除指定客戶端外的所有已連接客戶端,由連接ID標識。
Clients.Group(groupName, connectionId1, connectionId2).addContosoChatMessageToPage(name, message);

指定組中除呼叫客戶端外的所有已連接客戶端。
Clients.OthersInGroup(groupName).addContosoChatMessageToPage(name, message);

由userId標識的特定用戶。
Clients.User(userid).addContosoChatMessageToPage(name, message);
(默認情況下,這是IPrincipal.Identity.Name可以通過向全局主機注冊IUserIdProvider的實現來更改的。)

連接ID列表中的所有客戶端和組。
Clients.Clients(ConnectionIds).broadcastMessage(name, message);

組ID列表中的所有組。
Clients.Groups(GroupIds).broadcastMessage(name, message);

用戶名標識的客戶端。
Clients.Client(username).broadcastMessage(name, message);

用戶名列表對應的所有客戶端(在SignalR 2.1中引入)。
Clients.Users(new string[] { "myUser", "myUser2" }).broadcastMessage(name, message);

 

參考資料

Tutorial: Get started with ASP.NET Core SignalR
https://docs.microsoft.com/en-us/aspnet/core/tutorials/signalr?view=aspnetcore-3.1&tabs=visual-studio

Manage users and groups in SignalR
https://docs.microsoft.com/en-us/aspnet/core/signalr/groups?view=aspnetcore-3.1#groups-in-signalr

ASP.NET SignalR 系列教程
https://www.cnblogs.com/fei686868/tag/SignalR/

ASP.NET Core SignalR CORS 跨域問題
https://www.cnblogs.com/IT-Ramon/p/12156832.html

signalR服務端調用客戶端方法說明
https://blog.csdn.net/niuc321/article/details/80348108


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM