SignalR在WebForm正常但MVC5(VS2019)Hub无法启动求助
Hey there, let's break down why your SignalR Hub isn't initializing in your MVC5 project even though it works perfectly in WebForms. I’ve gone through your code and have several key fixes and checks to get this up and running:
1. Add Explicit SignalR Startup Configuration
Unlike WebForms, MVC5 requires a dedicated Startup class to configure SignalR—this is likely the biggest missing piece. Create or update a Startup.cs file in your project root:
using Microsoft.Owin; using Owin; [assembly: OwinStartup(typeof(SignalRArrayList.Startup))] namespace SignalRArrayList { public class Startup { public void Configuration(IAppBuilder app) { // Map SignalR to its default route app.MapSignalR(); } } }
Also, make sure you have these critical NuGet packages installed: Microsoft.Owin, Microsoft.Owin.Cors, and Microsoft.AspNet.SignalR.Owin.
2. Validate Your Hub Class Setup
Double-check your MyHub class to ensure it’s properly configured for SignalR to detect it:
using Microsoft.AspNet.SignalR; namespace SignalRArrayList { // Must be public and inherit from Hub public class MyHub : Hub { public static void SendMessages() { // Get the hub context to broadcast to all clients var hubContext = GlobalHost.ConnectionManager.GetHubContext<MyHub>(); hubContext.Clients.All.updateMessages(); } } }
SignalR camel-cases hub names by default, so myHub in your JavaScript matches the MyHub class name correctly—no issues here, but accessibility (public) is non-negotiable.
3. Fix JavaScript Routing and Error Handling
Your view code has a few subtle bugs that could be causing silent failures. Here’s the corrected version with error logging to catch hidden issues:
@{ ViewBag.Title = "About"; } <div> <table id="tbl"></table> </div> @section scripts{ <script src="~/Scripts/jquery-3.3.1.min.js"></script> <script src="~/Scripts/jquery.signalR-2.4.1.min.js"></script> <!-- Use root-relative path with tilde to play nice with MVC routing --> <script src="~/signalR/hubs"></script> <script type="text/javascript"> $(function () { // Add error logging to catch connection issues $.connection.hub.error(function(error) { console.log('SignalR Error: ' + error); alert('SignalR Error: ' + error); }); var job = $.connection.myHub; job.client.updateMessages = function () { getData(); }; // Start connection with status handlers $.connection.hub.start() .done(function() { console.log('SignalR Connected Successfully'); }) .fail(function(error) { console.log('SignalR Connection Failed: ' + error); alert('Connection Failed: ' + error); }); getData(); }); function getData() { var $tbl = $('#tbl'); $.ajax({ // Use MVC's Url.Action to avoid hardcoding paths url: '@Url.Action("GetAllMessages", "Home")', contentType: "application/json; charset=utf-8", dataType: "json", type: "POST", success: function (data) { // MVC doesn't wrap WebMethod responses in data.d (that's a WebForms quirk!) if (data.length > 0) { $tbl.empty(); $tbl.append('<tr><th>ID</th><th>Back 1</th><th>Lay 1</th></tr>'); var rows = []; for (var i = 0; i < data.length; i++) { // Fixed typo: bacl1 → back1, removed non-existent QuantDecimal field rows.push('<tr><td>' + data[i].id + '</td><td>' + data[i].back1 + '</td><td>' + data[i].lay1 + '</td></tr>'); } $tbl.append(rows.join('')); } }, error: function(xhr, status, error) { console.log('AJAX Error: ' + error); alert('AJAX Load Failed: ' + error); } }); } </script> }
Key fixes here:
- Swapped
/signalR/hubsfor~/signalR/hubsto work with MVC's routing - Added SignalR connection error handling to reveal silent failures
- Used
@Url.Actionfor the AJAX URL to avoid routing bugs - Removed the
data.dwrapper (MVC returns raw data, not wrapped like WebForms) - Fixed the
bacl1typo and removed the non-existentQuantDecimalfield (which would break table rendering)
4. Check SqlDependency Prerequisites
For your SQL query notifications to work:
- Enable Service Broker on your database with this SQL command:
ALTER DATABASE YourDatabaseName SET ENABLE_BROKER; - Ensure your application pool identity has the necessary permissions to access SQL Server Service Broker.
5. Verify NuGet Package Compatibility
Make sure all SignalR-related packages are on compatible versions (match your script version 2.4.1):
Microsoft.AspNet.SignalRMicrosoft.AspNet.SignalR.CoreMicrosoft.AspNet.SignalR.Owin
Mismatched or outdated packages often cause silent startup failures.
After applying these changes, run your project and check the browser console (F12) for errors—this will now show you exactly what’s going wrong instead of failing silently.
内容的提问来源于stack exchange,提问作者Rakesh Yadav

