In this article, we will know about a Minimal API return type that is 'Result.Stream()'
Result.Stream():
The 'Result.Steam()' can be used to deliver the stream of data as a response from the Minimal API endpoint. For example on consuming a third-party API from our minimal API endpoint, a common approach is to read the response from the third-party API and then deserialize the response and finally return the response using 'Result.Ok()'. But using 'Result.Stream()' return type we can directly return the stream of third-party API response without deserializing.
Create A .NET6 Minimal API Project:
Let's create a .Net6 Minimal API sample project to accomplish our demo. We can use either Visual Studio 2022 or Visual Studio Code(using .NET CLI commands) to create any.Net6 application. For this demo, I'm using the 'Visual Studio Code'(using the .NET CLI command) editor.
CLI command For Minimal API Project
dotnet new webapi -minimal -o Your_Project_Name
dotnet new webapi -minimal -o Your_Project_Name
Now register our third-party API with the HttpClient instance in the DI services.
builder.Services .AddScoped(hc => new HttpClient { BaseAddress = new Uri("https://jsonplaceholder.typicode.com/") });
'Result.Ok()'(Common Technique Involves In Deserialization):
Now let's implement a minimal API endpoint that going to consume a third-party API, so this old or traditional approach after receiving a stream of data from the API and then deserialize the data and then return response using 'Result.Ok()'.
app.MapGet("test-api", async (HttpClient httpClient) => { List<Post> posts = await httpClient.GetFromJsonAsync<List<Post>>("posts"); return Results.Ok(posts); });
- (Line: 3) Here we observe third-party API response deserialized with help of the 'GetFromJsonAsync<T>' method.
- (Line: 4) Using 'Results.Ok' sending the response to the client.'
'Result.Stream()' (Returns Stream Of Response Directly):
Using 'Resul.Stream()' response delivered directly from the minimal API endpoint without any deserialization.
app.MapGet("test-api", async (HttpClient httpClient) => { var streamResponse = await httpClient.GetStreamAsync("posts"); return Results.Stream(streamResponse, "application/json"); });
- (Line: 3-4) Reading the third-party API response as stream and then using 'Result.Stream()' returns the stream response directly by specify 'content-type'(eg:- application/json).
Support Me!
Buy Me A Coffee
PayPal Me
Video Session:
Wrapping Up:
Hopefully, I think this article delivered some useful information on 'Result.Stream()' a return type of a Minimal API endpoint. I love to have your feedback, suggestions, and better techniques in the comment section below.
Comments
Post a Comment