Skip to content

Use Pipelines in PlaintextApp sample #7227

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
merged 5 commits into from
May 25, 2019
Merged
Changes from 3 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
45 changes: 35 additions & 10 deletions src/Servers/Kestrel/samples/PlaintextApp/Startup.cs
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using System.IO;
using System.IO.Pipelines;
using System.Net;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;

namespace PlaintextApp
{
Expand All @@ -16,16 +20,19 @@ public class Startup

public void Configure(IApplicationBuilder app)
{
app.Run((httpContext) =>
{
var response = httpContext.Response;
response.StatusCode = 200;
response.ContentType = "text/plain";

var helloWorld = _helloWorldBytes;
response.ContentLength = helloWorld.Length;
return response.Body.WriteAsync(helloWorld, 0, helloWorld.Length);
});
app.Run(Plaintext);
}

private static Task Plaintext(HttpContext httpContext)
{
var payload = _helloWorldBytes;
var response = httpContext.Response;

response.StatusCode = 200;
response.ContentType = "text/plain";
response.ContentLength = payload.Length;

return response.BodyPipe.WriteAsync(payload).GetAsTask();
}

public static Task Main(string[] args)
Expand All @@ -42,4 +49,22 @@ public static Task Main(string[] args)
return host.RunAsync();
}
}

internal static class ValueTaskExtensions
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Task GetAsTask<T>(this in ValueTask<T> valueTask)
{
if (valueTask.IsCompletedSuccessfully)
{
// Signal consumption to the IValueTaskSource
valueTask.GetAwaiter().GetResult();
return Task.CompletedTask;
}
else
{
return valueTask.AsTask();
}
}
}
}