Hướng dẫn dùng connectapi JavaScript
Skip to main content This browser is no longer supported. Show
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support. ASP.NET SignalR Hubs API Guide - JavaScript Client
In this articleWarning This documentation isn't for the latest version of SignalR. Take a look at ASP.NET Core SignalR.
OverviewThis document contains the following sections:
For documentation on how to program the server or .NET clients, see the following resources:
The SignalR 2 server component is only available on .NET 4.5 (though there is a .NET client for SignalR 2 on .NET 4.0). The generated proxy and what it does for youYou can program a JavaScript client to communicate with a SignalR service with or without a proxy that SignalR generates for you. What the proxy does for you is simplify the syntax of the code you use to connect, write methods that the server calls, and call methods on the server. When you write code to
call server methods, the generated proxy enables you to use syntax that looks as though you were executing a local function: you can write For example, suppose you have the following Hub class on the server:
The following code examples show what JavaScript code looks like for invoking the With the generated proxy
Without the generated proxy
When to use the generated proxyIf you want to register multiple event handlers for a client method that the server calls, you can't
use the generated proxy. Otherwise, you can choose to use the generated proxy or not based on your coding preference. If you choose not to use it, you don't have to reference the "signalr/hubs" URL in a Client setupA JavaScript client requires references to jQuery and the SignalR core JavaScript file. The jQuery version must be 1.6.4 or major later versions, such as 1.7.2, 1.8.2, or 1.9.1. If you decide to use the generated proxy, you also need a reference to the SignalR generated proxy JavaScript file. The following example shows what the references might look like in an HTML page that uses the generated proxy.
These references must be included in this order: jQuery first, SignalR core after that, and SignalR proxies last. How to reference the dynamically generated proxyIn the preceding example, the reference to the SignalR generated
proxy is to dynamically generated JavaScript code, not to a physical file. SignalR creates the JavaScript code for the proxy on the fly and serves it to the client in response to the "/signalr/hubs" URL. If you specified a different base URL for SignalR connections on the server in your In an ASP.NET MVC 4 or 5 Razor view, use the tilde to refer to the application root in your proxy file reference:
For more information about using SignalR in MVC 5, see Getting Started with SignalR and MVC 5. In an ASP.NET MVC 3 Razor view, use
In an ASP.NET Web Forms application, use
As a general rule, use the same method for specifying the "/signalr/hubs" URL that you use for CSS or JavaScript files. If you specify a URL without using a tilde, in some scenarios your application will work correctly when you test in Visual Studio using IIS Express but will fail with a 404 error when you deploy to full IIS. For more information, see Resolving References to Root-Level Resources in Web Servers in Visual Studio for ASP.NET Web Projects on the MSDN site. When you run a web project in Visual Studio 2017 in debug mode, and if you use Internet Explorer as your browser, you can see the proxy file in Solution Explorer under Scripts. To see the contents of the file, double-click hubs. If you are
not using Visual Studio 2012 or 2013 and Internet Explorer, or if you are not in debug mode, you can also get the contents of the file by browsing to the "/signalR/hubs" URL. For example, if your site is running at How to create a physical file for the SignalR generated proxyAs an alternative to the dynamically generated proxy, you can create a physical file that has the proxy code and reference that file. You might want to do that for control over caching or bundling behavior, or to get IntelliSense when you are coding calls to server methods. To create a proxy file, perform the following steps:
How to establish a connectionBefore you can establish a connection, you have to create a connection object, create a proxy, and register event handlers for methods that can be called from the server. When the proxy and event handlers are set up, establish the connection by calling the If you are using the generated proxy, you don't have to create the connection object in your own code because the generated proxy code does it for you. Establish a connection (with the generated proxy)
Establish a connection (without the generated proxy)
The sample code uses the default "/signalr" URL to connect to your SignalR service. For information about how to specify a different base URL, see ASP.NET SignalR Hubs API Guide - Server - The /signalr URL. By default, the hub location is the current server; if you are connecting to a different server, specify the URL before calling the
Note Normally you register event handlers before calling
the $.connection.hub is the same object that $.hubConnection() createsAs you can see from the examples, when you use the generated
proxy, When you're using the
generated proxy, you can do anything with Asynchronous execution of the start methodThe If you put the "Now connected" statement from the preceding example as the next
line of code after the How to establish a cross-domain connectionTypically if the browser loads a page from In SignalR 1.x, cross domain requests were controlled by a single EnableCrossDomain flag. This flag controlled both JSONP and CORS requests. For greater flexibility, all CORS support has been removed from the server component of SignalR (JavaScript clients still use CORS normally if it is detected that the browser supports it), and new OWIN middleware has been made available to support these scenarios. If JSONP is required on the client (to support cross-domain requests in older browsers), it will need to be enabled explicitly by setting Adding Microsoft.Owin.Cors to your project: To install this library, run the following command in the Package Manager Console:
This command will add the 2.1.0 version of the package to your project. Calling UseCorsThe following code snippet demonstrates how to implement cross-domain connections in SignalR 2. Implementing cross-domain requests in SignalR 2 The following code demonstrates how to enable CORS or
JSONP in a SignalR 2 project. This code sample uses
Note
How to configure the connectionBefore you establish a connection, you can specify query string parameters or specify the transport method. How to specify query string parametersIf you want to send data to the server when the client connects, you can add query string parameters to the connection object. The following examples show how to set a query string parameter in client code. Set a query string value before calling the start method (with the generated proxy)
Set a query string value before calling the start method (without the generated proxy)
The following example shows how to read a query string parameter in server code.
How to specify the transport methodAs part of the process of connecting, a SignalR client normally negotiates with the server to determine the best transport that is supported by both server and client. If you already know which transport you want to use, you can bypass this negotiation process by specifying the transport method when you call the Client code that specifies the transport method (with the generated proxy)
Client code that specifies the transport method (without the generated proxy)
As an alternative, you can specify multiple transport methods in the order in which you want SignalR to try them: Client code that specifies a custom transport fallback scheme (with the generated proxy)
Client code that specifies a custom transport fallback scheme (without the generated proxy)
You can use the following values for specifying the transport method:
The following examples show how to find out which transport method is being used by a connection. Client code that displays the transport method used by a connection (with the generated proxy)
Client code that displays the transport method used by a connection (without the generated proxy)
For information about how to check the transport method in server code, see ASP.NET SignalR Hubs API Guide - Server - How to get information about the client from the Context property. For more information about transports and fallbacks, see Introduction to SignalR - Transports and Fallbacks. How to get a proxy for a Hub classEach connection object that you create encapsulates information about a connection to a SignalR service that contains one or more Hub classes. To communicate with a Hub class, you use a proxy object which you create yourself (if you're not using the generated proxy) or which is generated for you. On the client the proxy name is a camel-cased version of the Hub class name. SignalR automatically makes this change so that JavaScript code can conform to JavaScript conventions. Hub class on server
Get a reference to the generated client proxy for the Hub
Create client proxy for the Hub class (without generated proxy)
If you decorate your Hub class with a Hub class on server with HubName attribute
Get a reference to the generated client proxy for the Hub
Create client proxy for the Hub class (without generated proxy)
How to define methods on the client that the server can callTo define a method that the server can call from a Hub, add an event handler to the Hub proxy by using the Add the event handler before you call the Method name matching is case-insensitive. For example, Define method on client (with the generated proxy)
Alternate way to define method on client (with the generated proxy)
Define method on client (without the generated proxy, or when adding after calling the start method)
Server code that calls the client method
The following examples include a complex object as a method parameter. Define method on client that takes a complex object (with the generated proxy)
Define method on client that takes a complex object (without the generated proxy)
Server code that defines the complex object
Server code that calls the client method using a complex object
How to call server methods from the clientTo call a server method from the client, use the Pass in a camel-case version of the method name on the Hub. SignalR automatically makes this change so that JavaScript code can conform to JavaScript conventions. The following examples show how to call a server method that doesn't have a return value and how to call a server method that does have a return value. Server method with no HubMethodName attribute
Server code that defines the complex object passed in a parameter
Client code that invokes the server method (with the generated proxy)
Client code that invokes the server method (without the generated proxy)
If you decorated the Hub method with a Server method with a HubMethodName attribute
Client code that invokes the server method (with the generated proxy)
Client code that invokes the server method (without the generated proxy)
The preceding examples show how to call a server method that has no return value. The following examples show how to call a server method that has a return value. Server code for a method that has a return value
The Stock class used for the return value
Client code that invokes the server method (with the generated proxy)
Client code that invokes the server method (without the generated proxy)
How to handle connection lifetime eventsSignalR provides the following connection lifetime events that you can handle:
For example, if you want to display warning messages when there are connection problems that might cause noticeable delays, handle the Handle the connectionSlow event (with the generated proxy)
Handle the connectionSlow event (without the generated proxy)
For more information, see Understanding and Handling Connection Lifetime Events in SignalR. How to handle errorsThe SignalR JavaScript client provides an If
you don't explicitly enable detailed error messages on the server, the exception object that SignalR returns after an error contains minimal information about the error. For example, if a call to
The following example shows how to add a handler for the error event. Add an error handler (with the generated proxy)
Add an error handler (without the generated proxy)
The following example shows how to handle an error from a method invocation. Handle an error from a method invocation (with the generated proxy)
Handle an error from a method invocation (without the generated proxy)
If a method invocation fails, the How to enable client-side loggingTo enable client-side logging on a connection, set the Enable logging (with the generated proxy)
Enable logging (without the generated proxy)
To see the logs, open your browser's developer tools and go to the Console tab. For a tutorial that shows step-by-step instructions and screen shots that show how to do this, see Server Broadcast with ASP.NET Signalr - Enable Logging. |