You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

同局域网Web应用向Windows服务发通知的方法及SignalR可行性咨询

Is SignalR a viable solution?

Absolutely! SignalR was built specifically for real-time server-to-client communication scenarios like this. Since all your apps are C#-based, it integrates seamlessly with both your ASP.NET web app and Windows services—this is exactly the kind of use case it’s designed for.

High-Level Architecture

Here’s the core flow to make this work:

  • Your web app hosts a SignalR Hub—this acts as the central messaging broker for all communication.
  • Each Windows service runs a SignalR client that maintains a persistent connection to the hub.
  • When a file upload completes successfully, your web app uses the hub to push a notification to all connected Windows service clients.
Step-by-Step Implementation

1. Set up SignalR in Your Web App

First, get SignalR installed and configured in your web application:

  • Install the NuGet package: Install-Package Microsoft.AspNet.SignalR (use Microsoft.AspNetCore.SignalR if you’re on ASP.NET Core instead of .NET Framework)
  • Create a SignalR Hub class to handle messaging:
    using Microsoft.AspNet.SignalR;
    
    public class FileUploadNotificationHub : Hub
    {
        // This method is called by the web app to broadcast notifications
        public void BroadcastUploadAlert(string fileName, string fileServerPath)
        {
            // Send the notification to all connected clients
            Clients.All.ReceiveFileUploadNotification(fileName, fileServerPath);
        }
    }
    
  • Configure SignalR in your startup code:
    For OWIN-based apps, add this to Startup.cs:
    using Owin;
    using Microsoft.AspNet.SignalR;
    
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // Map SignalR to the default endpoint (/signalr)
            app.MapSignalR();
        }
    }
    
    If you’re using an older ASP.NET app without OWIN, register SignalR in Global.asax:
    protected void Application_Start()
    {
        RouteTable.Routes.MapHubs();
    }
    

2. Turn Your Windows Services into SignalR Clients

Each Windows service needs to connect to the hub and listen for notifications:

  • Install the SignalR client NuGet package: Install-Package Microsoft.AspNet.SignalR.Client
  • In your Windows service’s OnStart method, initialize the connection and set up the listener:
    using Microsoft.AspNet.SignalR.Client;
    using System.ServiceProcess;
    
    public class FileMonitorService : ServiceBase
    {
        private HubConnection _hubConnection;
        private IHubProxy _hubProxy;
    
        protected override void OnStart(string[] args)
        {
            // Connect to your web app's SignalR hub
            var hubUrl = "http://your-web-server-ip-or-domain/signalr";
            _hubConnection = new HubConnection(hubUrl);
            _hubProxy = _hubConnection.CreateHubProxy("FileUploadNotificationHub");
    
            // Register the client method that handles incoming notifications
            _hubProxy.On<string, string>("ReceiveFileUploadNotification", (fileName, filePath) =>
            {
                // Add your custom logic here—e.g., fetch the file, process it, log the event
                System.Diagnostics.EventLog.WriteEntry(
                    "FileMonitorService",
                    $"New file uploaded: {fileName} | Server path: {filePath}",
                    System.Diagnostics.EventLogEntryType.Information
                );
            });
    
            // Start the connection with basic error handling
            try
            {
                _hubConnection.Start().Wait();
            }
            catch (Exception ex)
            {
                System.Diagnostics.EventLog.WriteEntry(
                    "FileMonitorService",
                    $"Failed to connect to SignalR hub: {ex.Message}",
                    System.Diagnostics.EventLogEntryType.Error
                );
                // Add retry logic here if needed
            }
    
            // Add auto-reconnect logic for network drops
            _hubConnection.Closed += async () =>
            {
                await Task.Delay(5000); // Wait 5 seconds before retrying
                try
                {
                    await _hubConnection.Start();
                }
                catch { /* Handle repeated retry failures */ }
            };
        }
    
        protected override void OnStop()
        {
            // Clean up the connection when the service stops
            _hubConnection?.Stop();
            _hubConnection?.Dispose();
        }
    }
    

3. Trigger the Notification After File Upload

In your web app’s file upload endpoint, confirm the file is saved, then send the notification via SignalR:

using Microsoft.AspNet.SignalR;
using System.Web.Mvc;

public class UploadController : Controller
{
    [HttpPost]
    public ActionResult UploadFile(HttpPostedFileBase file)
    {
        if (file == null || file.ContentLength == 0)
            return Json(new { Success = false, Message = "No file selected" });

        // Save the file to your server's storage
        var uploadDir = Server.MapPath("~/Uploads/");
        System.IO.Directory.CreateDirectory(uploadDir);
        var fullPath = System.IO.Path.Combine(uploadDir, file.FileName);
        file.SaveAs(fullPath);

        // Get the SignalR hub context and broadcast the notification
        var hubContext = GlobalHost.ConnectionManager.GetHubContext<FileUploadNotificationHub>();
        hubContext.Clients.All.ReceiveFileUploadNotification(
            file.FileName,
            fullPath
        );

        return Json(new { Success = true, Message = "File uploaded and notifications sent" });
    }
}
Key Considerations
  • Network Access: Ensure all PCs running the Windows service can reach your web server’s SignalR endpoint (check firewall rules for port 80/443, or your web app’s custom port).
  • Authentication: If you need to restrict hub access, add authentication (e.g., Windows Auth or API keys). Validate connections in the hub’s OnConnected method.
  • Logging: Add detailed logging to both the web app and Windows services to troubleshoot connection issues or missed notifications.
  • Scalability: If you ever scale your web app across multiple servers, use a SignalR backplane (like Redis or SQL Server) to ensure notifications reach all clients regardless of which server they’re connected to.

内容的提问来源于stack exchange,提问作者NoughT

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:36:57