Question

I know that this question has been asked multiple times but I tried all the solutions given and none seem to fit my problem.

I am getting the following error :

0x800a138f - JavaScript runtime error: Unable to get property 'chatHub' of undefined or null reference.

The error come randomly, sometime when I run my webapp it happens, sometime it doesn't and I am able to run my app and use the hub normally.

Script in Index page:

@section scripts
{
    <script src="Scripts/jquery.signalR-2.0.3.js" type="text/javascript"></script>
    <script src="signalr/hubs" type="text/javascript"></script>
    <script type="text/javascript">
    $(function () {
        var chatHub = $.connection.chatHub;

        chatHub.client.add = function (message) {
            $('#listMessages').append('<li>' + message + '</li>');
        };

        $.connection.hub.start().done(function () {
            $('#SendMessage').click(function () {
                var message = $('#txtMessage').val();
                chatHub.server.send($('#who').val(), message);
                $('#listMessages').append('<li>' + 'You said : ' + message + '</li>');
            })
        });
    })
</script>

}

The layout is the default layout for internet MVC app from visual studio which contains :

@Scripts.Render("~/bundles/jquery")

My simple hub :

[HubName("chatHub")]
public class ChatHub : Hub
{
    public void send(string sendTo, string message)
    {
        base.Clients.Group(sendTo).add(Context.User.Identity.Name + " said : " + message);
    }

    public override Task OnConnected()
    {
        base.Groups.Add(Context.ConnectionId,  Context.User.Identity.Name);
        return base.OnConnected();
    }
}

For some reason, I keep getting the error randomly. How can I fix it? Thanks!

Edit: After following the advice from DaveB, I used Fiddler to check and it seems like it is requesting for signalr/hubs not from /signalr/hubs but from /mycontroller/signalr/hubs which is not a valid address (same error for jquery-signalr js). How can I fix this ?

Was it helpful?

Solution

Change the script load to <script src="/signalr/hubs"></script> (note the initial forward slash) so it loads from the root rather than relative to the current directory.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top