问题
It's almost 12 hrs no success, I have tried this code in Web Project and it worked but when integrating with my MVC application it is giving me errors
GET http://localhost:50843/signalr/Hubs
DashBoard:553 Uncaught TypeError: Cannot read property 'client' of undefined(anonymous function) @ DashBoard:553
This error occurs usually when the hub script is not found I have tried many fixes but no luck here is my code.
Project structure
References
ChatHub.cs (I have omitted the method implementation)
using System;
using System.Web;
using Microsoft.AspNet.SignalR;
using SignalRTest;
using System.Threading.Tasks;
using System.Linq;
using System.Web.Security;
namespace SignalRChat
{
public class ChatHub : Hub
{
}
}
Startup.cs
using Microsoft.AspNet.SignalR;
using Microsoft.Owin;
using Owin;
[assembly: OwinStartup(typeof(SignalRChat.Startup))]
namespace SignalRChat
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR();
}
}
}
_Layout.cshtml
This is the problem area not able to invoke the client object.Any help will be greatly appreciated.
Thanks in advance.
回答1:
In the client code you should include both jquery.min.js, as well as jquery.signalR.min.js (From what I see in your cshtml you are only including jquery.signalR).
Try including both and see if it works!
Best of luck!
EDIT: You should put your entire client code inside $(function(){ });
Example from the official documentation:
<script type="text/javascript">
$(function () {
var chat = $.connection.chatHub;
chat.client.broadcastMessage = function (name, message) {
var encodedName = $('<div />').text(name).html();
var encodedMsg = $('<div />').text(message).html();
$('#discussion').append('<li><strong>' + encodedName
+ '</strong>: ' + encodedMsg + '</li>');
};
$('#displayname').val(prompt('Enter your name:', ''));
$('#message').focus();
$.connection.hub.start().done(function () {
$('#sendmessage').click(function () {
chat.server.send($('#displayname').val(), $('#message').val());
$('#message').val('').focus();
});
});
});
</script>
Notice how the client code is wrapped inside a jQuery function.
Best of luck!
回答2:
I actually applied a break point at Startup.cs file to see if it is invokin gthe method MapSignalR() as this is the method which is responsible for invoking the hub script dynamically. And to my surprise this method is not getting invoked.
So after some more efforts I realized I was missing these references Microsoft.Owin.Host.SystemWeb and Microsoft.Owin.Security that are responsible to invoke the Startup class method through Owin.
来源:https://stackoverflow.com/questions/32033479/signalr-2-2-0-mvc-4-error-client-undefined