diff --git a/NLog.Web.AspNetCore/LayoutRenderers/AspNetRequestQueryStringLayoutRenderer.cs b/NLog.Web.AspNetCore/LayoutRenderers/AspNetRequestQueryStringLayoutRenderer.cs index 67fe127c..36bc9eb0 100644 --- a/NLog.Web.AspNetCore/LayoutRenderers/AspNetRequestQueryStringLayoutRenderer.cs +++ b/NLog.Web.AspNetCore/LayoutRenderers/AspNetRequestQueryStringLayoutRenderer.cs @@ -10,6 +10,7 @@ using NLog.Config; using NLog.Web.Enums; using System; +using System.Linq; using NLog.Web.Internal; namespace NLog.Web.LayoutRenderers @@ -29,6 +30,7 @@ public class AspNetQueryStringLayoutRenderer : AspNetLayoutRendererBase { /// /// List Query Strings' Key to be rendered from Request. + /// If empty, then render all querystrings /// public List QueryStringKeys { get; set; } @@ -46,41 +48,60 @@ public class AspNetQueryStringLayoutRenderer : AspNetLayoutRendererBase protected override void DoAppend(StringBuilder builder, LogEventInfo logEvent) { var httpRequest = HttpContextAccessor?.HttpContext?.TryGetRequest(); + if (httpRequest == null) + return; - if (this.QueryStringKeys?.Count > 0) - { - if (httpRequest == null) - return; - - var includeArrayEndBraces = false; - var firstItem = true; + var includeArrayEndBraces = false; + var firstItem = true; + + var allQueryStrings = this.QueryStringKeys == null || this.QueryStringKeys.Count == 0; + var queryStringKeys = this.QueryStringKeys; #if !NETSTANDARD_1plus - var queryStrings = httpRequest.QueryString; + var queryStrings = httpRequest.QueryString; + if (allQueryStrings) + { + queryStringKeys = new List(queryStrings.Keys.Count); + + foreach (var key in queryStrings.Keys) + { + if (key != null) + { + queryStringKeys.Add(key.ToString()); + } + } + } #else - var queryStrings = httpRequest.Query; + var queryStrings = httpRequest.Query; + if (allQueryStrings) + { + queryStringKeys = queryStrings.Keys.ToList(); + } #endif - if (queryStrings?.Count > 0) + + + + + if (queryStrings?.Count > 0) + { + foreach (var configuredKey in queryStringKeys) { - foreach (var configuredKey in this.QueryStringKeys) - { - // This platoform specific code is to prevent an unncessary .ToString call otherwise. + // This platoform specific code is to prevent an unncessary .ToString call otherwise. #if !NETSTANDARD_1plus - var value = queryStrings[configuredKey]; + var value = queryStrings[configuredKey]; #else - var value = queryStrings[configuredKey].ToString(); + var value = queryStrings[configuredKey].ToString(); #endif - if (!String.IsNullOrEmpty(value)) - { - this.AppendKeyAndValue(builder, configuredKey, value, firstItem, ref includeArrayEndBraces); - firstItem = false; - } + if (!String.IsNullOrEmpty(value)) + { + this.AppendKeyAndValue(builder, configuredKey, value, firstItem, ref includeArrayEndBraces); + firstItem = false; } } - - if (includeArrayEndBraces) - builder.Append(GlobalConstants.jsonArrayEndBraces); } + + if (includeArrayEndBraces) + builder.Append(GlobalConstants.jsonArrayEndBraces); } ///