1×
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.

Autoplay

    Expose Values for Real-time Consumption with SignalR in ASP.NET Core

    Fabian GosebrinkFabian Gosebrink
    javascriptJavaScript
    asp-netASP.NET
    chromeChrome

    Providing real time information to your Javascript apps with ASP.NET Core SignalR. With ASP.NET Core and SignalR you can add real time functionality with ease and keep your application up to date without letting the clients reloading their page manually.

    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Discuss

    Discuss

    Transcript

    Transcript

    Instructor: Let us start with the folder structure having a separate client and server folder. In the server folder, we will create a new Web API with the dotnet CLI anti command dotnet new webapi. Having done that, let's head over to Startup.cs file. For accepting requests from a different origin than the one our server is running on, we have to add CORS to the pipeline and of course SignalR as we want to use that as well. The extension method at SignalR is built-in and we can simply add it to a ServiceCollection to use SignalR. To configure CORS, we have to add a policy which we will name MyAllowSpecificOrigins, and configure this policy into ServiceCollection as well inside the ConfigureServices method. First, let us use CORS. For the sake of simplicity of this demo, we will allow any header, the origin. We run the client later on, allowing credentials and any method. Please do not use that one in production, as it is really open. However, we have to add CORS to the middleware as well, in the configure method with app.UseCors, passing it the name of the policy. We have to enable a route for SignalR as well, which we will do with the endpoint routing underneath. We can map a route, messages, to the not-yet existing Messages Hub, with the MapHub method from the endpoints. This route can get called from the client to a class which represents the interface, which can get invoked from the client-side's JavaScript. These classes are called Hubs. Let's create this message Hub next. Therefore, we create a folder called Hubs and add a class, Message, up in here. This is a normal C# class which inherits from the Hub class from the SignalR namespace. Inside that, we can place a method called SendMessage, which takes a string parameter called chat- message, and then broadcasts this message to all connected clients. We take SendBack as event name, and pass the given message as parameter. Let's our startup class know about this message Hub and head over to our client, where we find three JS files and one HTML file. The SignalR file comes from the signalr npm package directly. You can also download it from GitHub. I just copied it here. You can find the links in the description of this video. As SignalR does not need JQuery anymore to work, we only have JQuery in here to make access to the DOM elements easier. Otherwise, we would not need it for using SignalR. The index. html is the file which provides an input. We can type text in, a button to fire a request, and an unordered list to apply items to. The file chat.js should contain a logic, so let's start there. First, we define the URLs. As our server is running on localhost:5001, we also have to define the SignalR route we mapped in the style of .cs, as this is URL/Messages. Then we can establish the SignalR connection. Let us new this up to make it correct, and register on an event we send from the server called SendBack. This is the identifier we gave in the Hub method. The second parameter is a fat arrow function which takes the given parameter, so we just append it to our HTML list. After that, we can start the connection. This returns a promise, and we can log out the success. Finally, we have to add a click event handler to our button, which will call invoke on our SignalR connection to that given route, which is mapped to the Hub we just created. First parameter is the method we want to invoke, the second parameter is the parameter we want to pass. At the end, we reset the input. That's it. Let's start a server and client via console and see that in the browser. I opened up two different browsers to see the message going around. On the right-hand side in the console, we can see that the connection was established. We can now type something in the box and send it. With the click on the button, the JavaScript invokes the method on the SignalR connection, calls the Hub and broadcasts the message to all connected clients. We do catch the event and append the send message at the list. Fine, that works. How about the server-invoken actions on a normal PUT, POST, PATCH, or DELETE request? We can also handle that. Let's take a look at our controller. There, we can fire requests too. First, we can inject the HubContext to the constructor, because we added SignalR to our services in the startup file. We can inject a generic interface, IHubContext, into our controller, with our Hub getting passed as a type. Let's add a new POST method which will use the HubContext in the method, and send an event called ItemReceived. We're just passing the value we get given in the request body for the sake of simplicity. Let us prefix the controller route to API to be more precise, and head to our client files. Here, we first add the URLs and register to the event the server sends us now, ItemReceived. We are appending the item to the list again, but this time with a fromServerPost prefix. Then we head over to our HTML and add a new button, and just call it server-invoke, with an id, post-message, and add a click handler to it, which just posts a hard-coded string, Hello, to the backend. Let's start the browser again and click the old button first. This works. Now the new button. This works as well. This is how you can call Hub methods from JavaScript, react to them, and also react to events the server sends over in normal HTTP requests. All this with ASP.NET Core and SignalR.