Skip to content
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

${aspnet-request-posted-body}: Use Async reading to prevent "Synchronous operations are disallowed" #549

Merged
merged 3 commits into from
May 13, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
25 changes: 25 additions & 0 deletions src/NLog.Web.AspNetCore/Internal/TaskExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
#if NETSTANDARD

using System;
using System.Threading.Tasks;

namespace NLog.Web.Internal
{
internal static class TaskExtensions
{
public static void RunTaskSynchronously(this Task t)
{
var task = Task.Run(async () => await t);
task.Wait();
}

public static T RunTaskSynchronously<T>(this Task<T> t)
{
T result = default(T);
var task = Task.Run(async () => result = await t);
task.Wait();
return result;
}
}
}
#endif
9 changes: 9 additions & 0 deletions src/Shared/LayoutRenderers/AspNetRequestPostedBody.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System;
using System.IO;
using System.Text;
using System.Threading;
using NLog.Common;
using NLog.Config;
using NLog.LayoutRenderers;
Expand All @@ -10,6 +11,7 @@
using System.Web;
using HttpRequest = System.Web.HttpRequestBase;
#else
using System.Threading.Tasks;
using HttpRequest = Microsoft.AspNetCore.Http.HttpRequest;
#endif

Expand Down Expand Up @@ -70,7 +72,12 @@ private static string BodyToString(Stream body)
// Note: don't dispose the StreamReader, it will close the stream and that's unwanted. You could pass that that
// to the StreamReader in some platforms, but then the dispose will be a NOOP, so for platform compat just don't dispose
var bodyReader = new StreamReader(body);

#if NETSTANDARD
var content = bodyReader.ReadToEndAsync().RunTaskSynchronously();
304NotModified marked this conversation as resolved.
Show resolved Hide resolved
#else
var content = bodyReader.ReadToEnd();
#endif
return content;
}
finally
Expand All @@ -80,6 +87,8 @@ private static string BodyToString(Stream body)
}
}



private bool TryGetBody(HttpRequest httpRequest, long? contentLength, out Stream body)
{
body = null;
Expand Down