ASP.net signalr is a tool that was launched a few years ago for use by ASP.net developers to add real-time functionality to the application. As long as the ASP.net application must receive frequent asynchronous updates from the server (from the monitoring system to the game), it is a typical library use case. Over the years, I've also used it to refresh the UI in the CQRS architecture scenario and to implement a notification system similar to Facebook in the Socialware application. From a more technical point of view, the SIGNALR is an abstraction layer, built on the basis of a transmission mechanism that allows for real-time connectivity between fully compatible clients and servers. The client is typically a Web browser, and the server is typically a Web server, but both are not limited to this.
asp.net signalr belongs to asp.net Core 2.1. Although the overall programming model of the library is similar to the classic ASP.net programming model, the library itself is actually completely rewritten. However, as long as developers adapt to all aspects of change, should be able to quickly master the new program. This article describes how to use a new library in a canonical WEB application to monitor remote tasks that can be lengthy. setting up the environment
You may need the following multiple NuGet packages to use libraries: Microsoft.AspNetCore.SignalR and Microsoft.AspNetCore.SignalR.Client. The previous package provides core functionality; The latter package is a. NET client and is only required when building a. NET client application. This example uses the library through the Web client, and therefore requires the SIGNALR NPM package instead. This is covered in more detail later in this article. Note that using SIGNALR in the context of a WEB application based on an MVC application model is not a mandatory requirement. You can use the SIGNALR library service directly through the ASP.net Core console application, and you can also host SIGNALR server portions in a console application.
It is not surprising that the application's startup class needs to contain some specific code. Specifically, the SIGNALR service will be added to the system services collection and configured to be available for practical use. Figure 1 shows the typical state of a startup class that uses SIGNALR.
Figure 1:signalr asp.net startup class for Core applications
public class Startup
{public
void configureservices (iservicecollection services)
{
services. Addmvc ();
Services. ADDSIGNALR ();
} public
void Configure (Iapplicationbuilder app)
{
app. Usestaticfiles ();
App. Usedeveloperexceptionpage ();
SIGNALR app. USESIGNALR (routes =>
{
routes. Maphub<updaterhub> ("/updaterdemo");
Routes. Maphub<progresshub> ("/progressdemo");
});
App. Usemvcwithdefaultroute ();
}
}
The SIGNALR service configuration includes the definition of one or more server routes that are bound to one or more endpoints in the server-side environment. The Maphub<t> method links the specified name in the request URL to an instance of the Hub class. The Hub class is both the core of implementing the SIGNALR protocol and the location where client calls are processed. Create a Hub for each set of logically related calls that the server side intends to accept and process. The SIGNALR dialog consists of messages exchanged between the two parties, and the result of invoking the method on the other side may be unresponsive, either by receiving one or more responses or by just receiving an error notification. Any asp.net Core signalr server implementation will expose one or more Hub. In Figure 1, there are two Hub classes (Updaterhub and Progresshub) bound to unique strings that are internally used to generate the URL target of the actual call. Hub class
The Hub class in the SIGNALR application is an ordinary simple class that inherits from the hub base class. This base class is used only to remove the hassle of developers writing the same sample code again and again. The base class provides only an infrastructure and does not provide predefined behavior. Specifically, it defines the members in Figure 2.
Figure 2:hub members of the base class
Members |
Description |
Client |
Exposes the properties of the list of clients currently managed by the Hub. |
Context |
Exposes the properties of the current caller context, including information such as the connection ID and user declaration (if any). |
Group |
Exposes the properties of each client subset that may have been programmatically defined as a group in the full client list. Groups are typically created to broadcast specific messages to selected audiences. |
Onconnectedasync |
The virtual method that is invoked whenever a new client connects to the Hub. |
Ondisconnectedasync |
The virtual method that is invoked whenever a new client disconnects from the Hub. |
The simplest Hub class is as follows:
public class Progresshub:hub
{
}
Interestingly, if you use it from the Controller method in the context of the ASP.net Core MVC application, the Hub form is used directly. Almost all asp.net Core signalr examples, including chat examples, tend to bind directly between the client and the Hub, without the need for any form of mediation by the controller. In this case, the Hub will take a more tangible form:
public class Samplechat:hub
{
//invoked from outside the Hub public void Say (String message)
{
//Invoke method on the listening client (s) return Clients.All.InvokeAsync ("Said", the message);
}
}
Unlike the SIGNALR chat examples in the dozens of blog articles, the example in this article does not actually establish a two-way conversation between the client and the server. Although the connection was established from the client, the client does not send any other requests after this. Instead, the server monitors the progress of the task and pushes the data back to the client when appropriate. That is, the Hub class must use these methods just like the code above, only if the use case requires the client to call the public method directly. If it is a bit complicated, the following example is sufficient to illustrate this point. Monitoring Remote Tasks
Its specific scenario is this: the ASP.net Core application provides the user with an HTML interface to facilitate the user from triggering potentially lengthy remote tasks such as creating a report. Therefore, as a developer, you need to display a progress bar to keep feedback on progress (see Figure 3).
Figure 3: Monitoring the progress of remote tasks using SIGNALR
As you can guess, in this example, both the client and the server set up SIGNALR live sessions in the context of the same ASP.net Core project. In this development phase, the MVC project is fully functional and is extended using the startup code in Figure 1. Next, the client framework is set up. You need to complete this setting in all Razor (or pure HTML) views that interact with the SIGNALR endpoint.
To communicate with a SIGNALR endpoint in a Web browser, first add a reference to the SIGNALR JavaScript client library:
<script src= "~/scripts/signalr.min.js" >
</script>
This JavaScript file can be obtained in a variety of ways. The most recommended approach is to use the Node.js Package Manager (NPM) tool that is available on almost every development computer (especially after the release of Visual Studio version 2017). Through NPM, locate and install the ASP.net Core signalr client named @aspnet/signalr. It copies many JavaScript files to disk, but only one file is needed in most cases. Either way, this is simply a link to a JavaScript file, and there are many other ways to get this file, including copying it from an older version of the ASP.net Core signalr project. However, NPM is the only supported script acquisition that the team provides. Note also that the ASP.net Core signalr no longer relies on jQuery.
Another section of more specific JavaScript code is needed in the client application. In particular, you need the following code:
var progressconnection =
new Signalr.hubconnection ("/progressdemo");
Progressconnection.start ();
The connection established with the SIGNALR Hub matches the specified path. Rather, the name passed as a parameter to the hubconnection should be one of the names mapped to the middle of the boot class. Internally, the Hubconnection object prepares a URL string that is generated by concatenating the current server URL and the given name. This URL is processed only if it matches one of the configured routes. Also note that if the client and server are not the same WEB application, you must pass the full URL of the ASP.net Core application hosting the SIGNALR hub to Hubconnection, plus the Hub name.
The JavaScript Hub Connection object must then be opened through the Start method. You can use JavaScript commitments (especially the then method) or async/await in typescript to perform subsequent operations, such as initializing a user interface. A SIGNALR connection is uniquely identified by a string ID.
It is important to note that if a transport connection or server fails, the ASP.net Core signalr no longer supports automatic reconnection. In older versions, if a server failure occurs, the client attempts to re-establish the connection based on the scheduling algorithm. If successful, it will reopen the connection with the same ID. In Signalr Core, if a connection is interrupted, the client can only start the connection again through the Start method, which generates other connection instances with different connection IDs. Client Callback API
Another basic JavaScript code that is required is the JavaScript for the Hub callback, which refreshes the interface and reflects the progress on the server on the client. Although this code is written in the ASP.net Core signalr slightly different from the older version, the intent is exactly the same. This example has the following three methods that can be invoked from the server: Initprogressbar, UpdateProgressBar, and Clearprogressbar. Needless to say, you can use any name and signature. Here is an implementation example:
Progressconnection.on ("Initprogressbar", () => {
setprogress (0);
$ ("#notification"). Show ();
Progressconnection.on ("UpdateProgressBar", (perc) => {
setprogress (perc);
});
Progressconnection.on ("Clearprogressbar", () => {
setprogress);
$ ("#notification"). Hide ();
});
For example, if the Initprogressbar method is invoked from the server, the helper setprogress JavaScript function configures and displays the progress bar (this demo uses the launch progress bar component). Note that the JQuery library is used in your code, but only for updating the UI. As mentioned earlier, the client Signalr Core Library is no longer a jQuery plug-in. That is, if the UI is based on angular, you might not need to use jQuery at all. server-side events
Part of the missing solution is deciding when to call the client function. There are mainly the following two kinds of programs. One is invoked when a client invokes a server operation through a WEB API or controller endpoint. The other is called when the Hub is called directly by the client. Finally, you just need to decide where to write the code for the task that calls the callback client.
In the canonical chat example, all of this happens in the Hub: executing all the necessary logic and assigning the message to the appropriate connection. Monitoring remote tasks is another matter. It assumes that a business process is running in the background to notify progress in some way. Technically speaking, this process may be encoded in the Hub and a dialog between the client UI is established. You can also have the controller (API) trigger this process, and the Hub is only used to pass events to the client. More practical than this example is to encode this process in a layer below the controller level.
In summary, you can define the Hub class and use it at any time to decide when and whether to call the client function. What's interesting is what you need to inject the Hub instance into the controller or other business class. This demo injects the Hub into the controller but also performs exactly the same operations on other deeper classes. The example Taskcontroller is invoked directly from the client via JAVASCRIPT to trigger the remote task where the progress bar will display its progress:
public class Taskcontroller:controller
{
private readonly ihubcontext<progresshub> _ Progresshubcontext;
Public Taskcontroller (ihubcontext<progresshub> progresshubcontext)
{
_progresshubcontext = Progresshubcontext;
Public
Iactionresult lengthy ()
{//Perform the task and call back
}
}
Inject the Hub into the controller or any other class through the Ihubcontext<thub> interface. The Ihubcontext interface encapsulates the Hub instance, but it cannot be accessed directly. The message can be dispatched back to the UI, but the connection ID cannot be accessed (for example). Assume that the remote task is executing in the lengthy method and that you need to update the client progress bar in it:
Progresshubcontext
. Clients
. Client (Connid)
. InvokeAsync ("UpdateProgressBar", 45);
The connection ID can be retrieved from the hub class, but cannot be retrieved from the generic hub context as this example. Therefore, the easiest way to do this is to have the client method pass the connection string when the remote task is started:
public void lengthy ([Bind (prefix= ID)] string connid) {...}
Finally, the Controller class receives the SIGNALR connection ID, injects a Hub context, and uses the context method called by the untyped generic API (InvokeAsync method) to perform the operation. In this way, the Hub class does not have to contain any methods. If this is strange, see the code in BIT.LY/2DWD8SV. Summary
This article describes how to monitor remote tasks using the ASP.net Core signalr in the context of a WEB application. The hub is almost empty because all notification logic is built into the controller and is choreographed using a Hub context injected through DI. This is just the starting point for the long journey of ASP.net Core signalr. Next, I'll delve deeper into the infrastructure and explore the typed Hub.
Dino Esposito wrote more than 20 books and 1,000 articles in his 25-year career. Esposito is not only the author of the drama "Business Interruption", but also the Baxenergy digital strategy analyst who is busy writing software to help build an environment-friendly world. You can watch him on Twitter (@despos).
Original: https://msdn.microsoft.com/zh-cn/magazine/mt846469
. NET community news, depth good text, welcome to visit the public number article summary http://www.csharpkit.com