The basics on how to send SSEs from a dotnet backend are very well described in the post “Server-side Event Streams with Dotnet Core and TypeScript” by Wim Jongeneel, an Engineer located in Rotterdam. In fact, some of the code contained in the repo I’ll be drawing code from you will recognize as coming relatively straight from his post.
What is added in this demo above the extension methods of sending data down the wire with the aid of the
HttpResponse object is
how one can leverage dotnet minimal API infrastructure to decouple how your business code may send events from
the actual mechanics.
For this we introduce an object that implements
IResult- this interface is understood by the minimal API infrastructure and
marks the result of an HTTP endpoint:
By passing an
IAsyncEnumerable into a custom
IResult object we have a nice way of providing a source of elements
that can be mapped 1:1 to events sent to the client.
One constraint that we apply to the provided items is that they provide a
Name and a
Payload property which will be used
to define under what event name the data will be sent to the client.
Armed with this handling of an
IAsyncEnumerable one can use it in this way:
ProduceEvents could be anything, e.g. the return of a MediatR call or however you call your business logic.
In this case it is a simple demo function like this one:
Also of note is that in this code, a special “Close” event will be sent. In the spec there doesn’t seem to be anything specific to how the server can end the connection (It’s the client’s responsibility to say good-bye), but by having a special event we can trigger that the client should close the SSEs response.
In the next post we’ll have a look at how the data provided by the API can be put to good use in a web page.