Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
530 views
in Technique[技术] by (71.8m points)

jquery - Uncaught TypeError: Cannot read property 'hub' of undefined

I have problem with calling function on signalr hub disconnect.

here are my js references

<script src="~/js/jquery.min.js"></script>

<script src="~/SignalR/dist/browser/signalr.min.js"></script>

script inside cshtml file

 var connection = new signalR.HubConnectionBuilder()
.withUrl("/chatt", {
    accessTokenFactory: () => "testing"
})
.build();


connection.start().then(function () {
connection.invoke('GetConnectionId')
.then(function (connectionId) {
   //alert(connectionId);
   //removeConnectionID(connectionId);
})

}).catch(err => console.error(err));

 
$.connection.hub.disconnected(function () {
    removeConnectionID();
})

async function removeConnectionID() {
    await  $.get("/Chat/Test") ;
    }

on $.connection.hub.disconnected i get Uncaught TypeError: Cannot read property 'hub' of undefined. When i start typing $.connection. i dont see hub property at all.

here is my configure services

 public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<mojDbContext>(options=> options.UseSqlServer(Configuration.GetConnectionString("IB150198T")));
        services.AddControllersWithViews();

        services.AddMvc();
        services.AddDistributedMemoryCache();
        services.AddSession();
        
        services.AddSignalR();
       // services.AddSingleton<IUserIdProvider, UserProvider>();
    }

I saw somewhere that I should have reference to js file that is named something like "/SignalR/Hubs" but cant find it in client side library for signalR

any help is appreciated!!!

question from:https://stackoverflow.com/questions/65891862/uncaught-typeerror-cannot-read-property-hub-of-undefined

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You're confusing ASP.NET SignalR with ASP.NET Core SignalR.

Your code is using ASP.NET Core SignalR until you try to access $.connection.hub which was the pattern in ASP.NET SignalR.

You can look at the tutorial for ASP.NET Core SignalR here https://docs.microsoft.com/aspnet/core/tutorials/signalr?view=aspnetcore-5.0&tabs=visual-studio


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...