Use Server Sent Events (SSE) in ASP.NET Core

Tram Ho

Some web applications need to display real-time data. As soon as possible new data on the server should immediately be displayed to the user. Traditionally developers often polled the server periodically to check for new data. This approach has its own drawbacks and can prove inappropriate in certain cases. Wouldn’t it be good if the server notified the client of new data, instead of the client periodically checking with the server? That is exactly what the HTML5 Server Sent Event (SSE) allows you to do. In this article, you will learn what Server Sent Events is and how to develop an ASP.NET Core application that receives real-time data from the server.

Ajax polling and SSEs

Web applications that need to display real-time data often use polling technology to get the latest data from the server. For example, you can develop an ASP.NET web form application that uses periodic Ajax requests to the server to check for new data. Accordingly the web form will render itself and display the latest data. However, this technology has the following disadvantages:

  • The “polling” technology makes too many requests to the server if the polling frequency is short. This will burden the server.
  • When polling is performed, there is no way to tell the client whether new data is available on the server. The client can keep polling the server periodically even when no data is available. This is an unnecessary cost on the entire system.
  • Polling technology is less accurate. When polling frequency is decided by the client and it is independent of the server’s data availability, it may happen that the data is already available on the server but the client can only display new data after one. few interruptions.

Server Sent Events (SSEs) are sent by the server. Using SSE you can notify the client application whenever something interesting happens on the server such as new data. And the client can take appropriate actions, such as displaying new data to the user.

Example of using SSE with ASP.NET Core

To understand how SSE can be used in an ASP.NET Core application, you will develop an application like this:

The application has a page with the Start Listening button. Clicking this button will open a connection with the specified Event Source . The event source is responsible for sending data notifications back to the browser. After the event source sends data, the connection to the event source will be closed.

Start by creating a new ASP.NET Core web application and set it up as usual by adding different directories and starting the code.

NorthwindDbContext and Customer class

We need to get data from the Customer table and the Northwind database. This data will then be sent to the client. As such, add the following NorthwindDbContext and Customer classes:

The Customer bao class Customer bao of 4 public properties named CustomerID , CompanyName , ContactName and Country . The NorthwindContext class manages Customer DBSet .

DbContext will inject from the Startup.cs class as follows:

DbContext is received in HomeController as code below:

Process() action

In addition to the Index() action, the HomeController will have an additional action to work with the event source. That’s the Process() action:

Action Process() creates a StringBuilder for storing data that is sent back to the browser. The simple loop browses through Customer DbSet and captures each Customer object separately. This Customer object is converted into JSON using Json.Net . The SerializeObject() accepts a .NET object and returns the corresponding JSON data. So the JSON data collected will be pushed into the StringBuilder object. Notice how the data is pushed into the StringBuilder .

Also note how the data returned from the Process() action. The Content() of the base Controller class has two parameters (the data sent to the browser and its Content-Type ). Data comes from StringBuilder . Content-Type is specified as text/event-stream . This content type is required with SSEs. Here we have completed the server side code. Please pass through the code to the client.

Index view

The index view includes a simple form as shown below:

The form contains the Start Listening button and 3 <div> tags. headerDiv displays header message, footerDiv displays footer message, and tagerDiv displays data returned from server.

Jquery uses EventSource

Code Jquery implements SSE in the Index view as shown below:

The above code consists of 4 parts.

  • In the click event handler an EventSource is created to connect to /home/process . Therefore the EventSource object will attempt to open a connection to this specified resource.
  • If the connection was successfully opened, the open event will be generated by the EventSource object. Open events can be handled using the addEventListener() . The open event handler simply displays the message in headerDiv .
  • If there is any error in the error event communication, it will be generated. Inside, you can check the eventPhase and take the appropriate action. In this case, the code checks whether the event source is closed or not. If closed it displays the message in footerDiv and also calls the close() of EventSource . If you do not call the close() the browser will trigger back to the source after 3 seconds. Calling close() ensures that the browser does not trigger the trigger event source. Of course, if you want to repeat the trigger, you don’t need to close the event source.
  • When the server sends the event notification to the browser, the event message is generated. The message event handler receives data using the property. In this case will be a single Customer object in JSON format. And the message will be generated many times depending on the data sent from the server. CustomerID and CompanyName are added to the targetDiv tag.

Resolve too long processing on the server side

In the example above, handling the server side is quite simple. However, at server-side processing times it can be quite long and a lot of data needs to be sent to the client. In such cases, it would be better to wait for the calculation of all the data to be neeus than sending small pieces. This way the client will get something from the server even if the server is still in processing (not yet complete). If you want to set up as a task you can edit the Process() action as shown below:

In this case, instead of using the Content() to return IActionResult , the code uses the Response object. The ContentType property of Response is set to text/event-stream . A loop through all of the Customer objects. Customer is converted into JSON as before and recorded to Response stream using WriteAsync method. The Flush() of the Response body ensures that data is pushed to the browser. The Close() closes the Response stream thus ending the event source.


This article helps you understand what Server Sent Events is and how to use it in ASP.NET Core. You can see it has a great advantage in applications that need to update real-time data (real-time), such as stocks, gold prices, weather, … Hope you have Useful things for me through this article. Thank you for watching.

Article translated from source:

Utilize Server Sent Events (SSE) In ASP.NET Core

Share the news now

Source : Viblo