Initialize Headers Dictionary Only Once (#4853)

Switch the  WebResponseObject.Headers Dictionary to initialize once instead of creating a new dictionary on every get. Moved logic to  WebResponseHelper.GetHeadersDictionary()  as this code will be reused outside of  WebResponseObject .

* [Feature] Create Headers Only Once and Only If Called

* {feature] headers -> _headers

* [Feature] Move logic to WebResponseObject for reuse

This code has potential reuse in InvokeRestMethodCommand. Moving it to WebResponseHelper

* Add comment to address PR Feedback.
This commit is contained in:
Mark Kraus authored and Ilya committed 2017-09-21 12:41:57 +04:00
1 parent b81aeb4b64
commit 5e24352177
2 files changed
+29 -11

No files matched your search

@@ -4,6 +4,8 @@
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Globalization;
@@ -16,6 +18,28 @@ namespace Microsoft.PowerShell.Commands
string characterSet = response.Content.Headers.ContentType.CharSet;
return characterSet;
}
internal static Dictionary<string, IEnumerable<string>> GetHeadersDictionary(HttpResponseMessage response)
{
var headers = new Dictionary<string, IEnumerable<string>>(StringComparer.OrdinalIgnoreCase);
foreach (var entry in response.Headers)
{
headers[entry.Key] = entry.Value;
}
// In CoreFX, HttpResponseMessage separates content related headers, such as Content-Type to
// HttpResponseMessage.Content.Headers. The remaining headers are in HttpResponseMessage.Headers.
// The keys in both should be unique with no duplicates between them.
// Added for backwards compatibility with PowerShell 5.1 and earlier.
if (response.Content != null)
{
foreach (var entry in response.Content.Headers)
{
headers[entry.Key] = entry.Value;
}
}
return headers;
}
internal static string GetProtocol(HttpResponseMessage response)
{
@@ -31,23 +31,17 @@ namespace Microsoft.PowerShell.Commands
{
get
{
var headers = new Dictionary<string, IEnumerable<string>>(StringComparer.OrdinalIgnoreCase);
foreach (var entry in BaseResponse.Headers)
if(_headers == null)
{
headers[entry.Key] = entry.Value;
}
if (BaseResponse.Content != null)
{
foreach (var entry in BaseResponse.Content.Headers)
{
headers[entry.Key] = entry.Value;
}
_headers = WebResponseHelper.GetHeadersDictionary(BaseResponse);
}
return headers;
return _headers;
}
}
private Dictionary<string, IEnumerable<string>> _headers = null;
/// <summary>
/// gets the RelationLink property
/// </summary>