-
Notifications
You must be signed in to change notification settings - Fork 25.1k
SSE return types /2 #35152
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
+175
−12
Merged
SSE return types /2 #35152
Changes from 9 commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
8cf446a
SSE return types /2
Rick-Anderson 8b46dde
SSE return types /2
Rick-Anderson 78059a9
SSE return types /2
Rick-Anderson d4454bc
SSE return types /2
Rick-Anderson 9c968a1
SSE return types /2
Rick-Anderson afedaef
fixes
Rick-Anderson 4afb5de
Update aspnetcore/fundamentals/minimal-apis/responses.md
Rick-Anderson 70c6b07
Apply suggestions from code review
Rick-Anderson 732f590
react to feedback
Rick-Anderson 979d782
Update aspnetcore/web-api/action-return-types/samples/10/ControllerSS…
Rick-Anderson 1da8e86
react to feedback
Rick-Anderson File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
4 changes: 4 additions & 0 deletions
4
aspnetcore/fundamentals/minimal-apis/10.0-samples/MinimalServerSentEvents/HeartRateRecord.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -120,7 +120,7 @@ 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 | ||
|
|
||
|
|
@@ -150,6 +150,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 | ||
|
|
||
|
||
| #### Text | ||
|
|
||
| :::code language="csharp" source="~/fundamentals/minimal-apis/9.0-samples/Snippets/Program.cs" id="snippet_08"::: | ||
|
|
@@ -172,6 +174,20 @@ The following example streams a video from an Azure Blob: | |
|
|
||
| [!code-csharp[](~/fundamentals/minimal-apis/resultsStream/7.0-samples/ResultsStreamSample/Program.cs?name=snippet_video)] | ||
|
|
||
| #### 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_item" ::: | ||
|
|
||
| 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. | ||
|
|
||
| #### Redirect | ||
|
|
||
| :::code language="csharp" source="~/fundamentals/minimal-apis/9.0-samples/Snippets/Program.cs" id="snippet_09"::: | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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. |
13 changes: 13 additions & 0 deletions
13
aspnetcore/web-api/action-return-types/samples/10/ControllerSSE/ControllerSSE.csproj
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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> |
15 changes: 15 additions & 0 deletions
15
aspnetcore/web-api/action-return-types/samples/10/ControllerSSE/ControllerSSE.http
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
68 changes: 68 additions & 0 deletions
68
...e/web-api/action-return-types/samples/10/ControllerSSE/Controllers/HeartRateController.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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)); | ||
| } | ||
| } | ||
4 changes: 4 additions & 0 deletions
4
aspnetcore/web-api/action-return-types/samples/10/ControllerSSE/HearRate.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); | ||
| } | ||
Rick-Anderson marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
28 changes: 28 additions & 0 deletions
28
aspnetcore/web-api/action-return-types/samples/10/ControllerSSE/Program.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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(); |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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
HearRatetoHeartRateRecordsee original https://github.com/captainsafia/minapi-sse/blob/main/Program.cs#L60-L63