Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
public record HeartRateRecord(DateTime Timestamp, int HeartRate)
{
public static HeartRateRecord Create(int heartRate) => new(DateTime.UtcNow, heartRate);
}
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I changed the name from HearRate to HeartRateRecord
see original https://github.com/captainsafia/minapi-sse/blob/main/Program.cs#L60-L63

Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
@baseUrl = http://localhost:5293
@baseUrl = http://localhost:58489

### Connect to SSE stream
# This request will open an SSE connection that stays open
Expand All @@ -12,4 +12,4 @@ Accept: text/event-stream
###

GET {{baseUrl}}/sse-item
Accept: text/event-stream
Accept: text/event-stream
Original file line number Diff line number Diff line change
Expand Up @@ -13,30 +13,32 @@ async IAsyncEnumerable<string> GetHeartRate(
while (!cancellationToken.IsCancellationRequested)
{
var heartRate = Random.Shared.Next(60, 100);
yield return $"Hear Rate: {heartRate} bpm";
yield return $"Heart Rate: {heartRate} bpm";
await Task.Delay(2000, cancellationToken);
}
}

return TypedResults.ServerSentEvents(GetHeartRate(cancellationToken), eventType: "heartRate");
return TypedResults.ServerSentEvents(GetHeartRate(cancellationToken),
eventType: "heartRate");
});
// </snippet_string>

// <snippet_json>
app.MapGet("/json-item", (CancellationToken cancellationToken) =>
{
async IAsyncEnumerable<HearRate> GetHeartRate(
async IAsyncEnumerable<HeartRateRecord> GetHeartRate(
[EnumeratorCancellation] CancellationToken cancellationToken)
{
while (!cancellationToken.IsCancellationRequested)
{
var heartRate = Random.Shared.Next(60, 100);
yield return HearRate.Create(heartRate);
yield return HeartRateRecord.Create(heartRate);
await Task.Delay(2000, cancellationToken);
}
}

return TypedResults.ServerSentEvents(GetHeartRate(cancellationToken), eventType: "heartRate");
return TypedResults.ServerSentEvents(GetHeartRate(cancellationToken),
eventType: "heartRate");
});
// </snippet_json>

Expand Down Expand Up @@ -64,7 +66,3 @@ async IAsyncEnumerable<SseItem<int>> GetHeartRate(

app.Run();

public record HearRate(DateTime Timestamp, int HeartRate)
{
public static HearRate Create(int heartRate) => new(DateTime.UtcNow, heartRate);
}
18 changes: 17 additions & 1 deletion aspnetcore/fundamentals/minimal-apis/responses.md
Original file line number Diff line number Diff line change
Expand Up @@ -120,14 +120,28 @@ In order to document this endpoint correctly the extension method `Produces` is

:::code language="csharp" source="~/fundamentals/minimal-apis/9.0-samples/Snippets/Program.cs" id="snippet_04":::

<a name="binr7"></a>
<a name="binr10"></a>

### Built-in results

[!INCLUDE [results-helpers](~/fundamentals/minimal-apis/includes/results-helpers.md)]

The following sections demonstrate the usage of the common result helpers.

#### Server-Sent Events (SSE)

The [TypedResults.ServerSentEvents](https://source.dot.net/#Microsoft.AspNetCore.Http.Results/TypedResults.cs,051e6796e1492f84) API supports returning a [ServerSentEvents](xref:System.Net.ServerSentEvents) result.

[Server-Sent Events](https://developer.mozilla.org/docs/Web/API/Server-sent_events) is a server push technology that allows a server to send a stream of event messages to a client over a single HTTP connection. In .NET, the event messages are represented as [`SseItem<T`>`](/dotnet/api/system.net.serversentevents.sseitem-1) objects, which may contain an event type, an ID, and a data payload of type `T`.

The [TypedResults](xref:Microsoft.AspNetCore.Http.TypedResults) class has a static method called [ServerSentEvents](https://source.dot.net/#Microsoft.AspNetCore.Http.Results/TypedResults.cs,ceb980606eb9e295) that can be used to return a `ServerSentEvents` result. The first parameter to this method is an `IAsyncEnumerable<SseItem<T>>` that represents the stream of event messages to be sent to the client.

The following example illustrates how to use the `TypedResults.ServerSentEvents` API to return a stream of heart rate events as JSON objects to the client:

:::code language="csharp" source="~/fundamentals/minimal-apis/10.0-samples/MinimalServerSentEvents/Program.cs" id="snippet_json" :::

For more information, see the [Minimal API sample app](https://github.com/dotnet/AspNetCore.Docs/blob/main/aspnetcore/fundamentals/minimal-apis/10.0-samples/MinimalServerSentEvents/Program.cs) using the `TypedResults.ServerSentEvents` API to return a stream of heart rate events as string, `ServerSentEvents`, and JSON objects to the client.

#### JSON

:::code language="csharp" source="~/fundamentals/minimal-apis/9.0-samples/Snippets/Program.cs" id="snippet_05":::
Expand All @@ -150,6 +164,8 @@ The preceding example returns a 500 status code.

:::code language="csharp" source="~/fundamentals/minimal-apis/9.0-samples/Snippets/Program.cs" id="snippet_12":::

#### Problem

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Were you planning to put something here?

#### Text

:::code language="csharp" source="~/fundamentals/minimal-apis/9.0-samples/Snippets/Program.cs" id="snippet_08":::
Expand Down
2 changes: 2 additions & 0 deletions aspnetcore/release-notes/aspnetcore-10.0.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ This section describes new features for minimal APIs.

[!INCLUDE[](~/release-notes/aspnetcore-10/includes/MinApiEmptyStringInFormPost.md)]

[!INCLUDE[](~/release-notes/aspnetcore-10/includes/sse.md)]

## OpenAPI

This section describes new features for OpenAPI.
Expand Down
17 changes: 17 additions & 0 deletions aspnetcore/release-notes/aspnetcore-10/includes/sse.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
### Support for Server-Sent Events (SSE)

ASP.NET Core now supports returning a [ServerSentEvents](xref:System.Net.ServerSentEvents) result using the [TypedResults.ServerSentEvents](https://source.dot.net/#Microsoft.AspNetCore.Http.Results/TypedResults.cs,051e6796e1492f84) API. This feature is supported in both Minimal APIs and controller-based apps.

Server-Sent Events is a server push technology that allows a server to send a stream of event messages to a client over a single HTTP connection. In .NET the event messages are represented as [`SseItem<T`>`](/dotnet/api/system.net.serversentevents.sseitem-1) objects, which may contain an event type, an ID, and a data payload of type `T`.

The [TypedResults](xref:Microsoft.AspNetCore.Http.TypedResults) class has a new static method called [ServerSentEvents](https://source.dot.net/#Microsoft.AspNetCore.Http.Results/TypedResults.cs,ceb980606eb9e295) that can be used to return a `ServerSentEvents` result. The first parameter to this method is an `IAsyncEnumerable<SseItem<T>>` that represents the stream of event messages to be sent to the client.

The following example illustrates how to use the `TypedResults.ServerSentEvents` API to return a stream of heart rate events as JSON objects to the client:

:::code language="csharp" source="~/fundamentals/minimal-apis/10.0-samples/MinimalServerSentEvents/Program.cs" id="snippet_json" :::

For more information, see:

- [Server-Sent Events](https://developer.mozilla.org/docs/Web/API/Server-sent_events) on MDN.
- [Minimal API sample app](https://github.com/dotnet/AspNetCore.Docs/blob/main/aspnetcore/fundamentals/minimal-apis/10.0-samples/MinimalServerSentEvents/Program.cs) using the `TypedResults.ServerSentEvents` API to return a stream of heart rate events as string, `ServerSentEvents`, and JSON objects to the client.
- [Controller API sample app](https://github.com/dotnet/AspNetCore.Docs/tree/main/aspnetcore/web-api/action-return-types/samples/10/ControllerSSE) using the `TypedResults.ServerSentEvents` API to return a stream of heart rate events as string, `ServerSentEvents`, and JSON objects to the client.
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.0-*" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
@baseUrl = http://localhost:5201/HeartRate

### Connect to SSE stream
# This request will open an SSE connection that stays open
GET {{baseUrl}}/string-item
Accept: text/event-stream

###
GET {{baseUrl}}/json-item
Accept: text/event-stream

###

GET {{baseUrl}}/sse-item
Accept: text/event-stream
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
using Microsoft.AspNetCore.Mvc;
using System.Runtime.CompilerServices;
using System.Net.ServerSentEvents;

[ApiController]
[Route("[controller]")]
Comment on lines +1 to +6
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@mikekistler should I remove the controller sample? If not, where should I surface it?


public class HeartRateController : ControllerBase
{
// /HeartRate/json-item
[HttpGet("json-item")]
public IResult GetHeartRateJson(CancellationToken cancellationToken)
{
async IAsyncEnumerable<HearRate> StreamHeartRates(
[EnumeratorCancellation] CancellationToken cancellationToken)
{
while (!cancellationToken.IsCancellationRequested)
{
var heartRate = Random.Shared.Next(60, 100);
yield return HearRate.Create(heartRate);
await Task.Delay(2000, cancellationToken);
}
}

return TypedResults.ServerSentEvents(StreamHeartRates(cancellationToken), eventType: "heartRate");
}

// /HeartRate/string-item
[HttpGet("string-item")]

public IResult GetHeartRateString(CancellationToken cancellationToken)
{
async IAsyncEnumerable<string> GetHeartRate(
[EnumeratorCancellation] CancellationToken cancellationToken)
{
while (!cancellationToken.IsCancellationRequested)
{
var heartRate = Random.Shared.Next(60, 100);
yield return $"Hear Rate: {heartRate} bpm";
await Task.Delay(2000, cancellationToken);
}
}

return TypedResults.ServerSentEvents(GetHeartRate(cancellationToken), eventType: "heartRate");
}

// /HeartRate/sse-item
[HttpGet("sse-item")]

public IResult GetHeartRateSSE(CancellationToken cancellationToken)
{
async IAsyncEnumerable<SseItem<int>> GetHeartRate(
[EnumeratorCancellation] CancellationToken cancellationToken)
{
while (!cancellationToken.IsCancellationRequested)
{
var heartRate = Random.Shared.Next(60, 100);
yield return new SseItem<int>(heartRate, eventType: "heartRate")
{
ReconnectionInterval = TimeSpan.FromMinutes(1)
};
await Task.Delay(2000, cancellationToken);
}
}

return TypedResults.ServerSentEvents(GetHeartRate(cancellationToken));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
public record HearRate(DateTime Timestamp, int HeartRate)
{
public static HearRate Create(int heartRate) => new(DateTime.UtcNow, heartRate);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
builder.Services.AddOpenApi();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.MapOpenApi();
}

app.UseHttpsRedirection();

app.UseAuthorization();


app.MapControllers();

app.MapGet("/", () => Results.Redirect("/HeartRate/json-item"));


app.Run();