From 437e8bf9b5ed8d0ba423635a1333d765c1cce6ee Mon Sep 17 00:00:00 2001 From: George <1641829+finsharp@users.noreply.github.com> Date: Thu, 10 Dec 2020 11:05:18 +0300 Subject: [PATCH] Set default Content-Type header to application/json when user has not specified `-ContentType` for PUT,POST,PATCH. (#486) Co-authored-by: George Ndungu --- .../Authentication/Cmdlets/InvokeMgGraphRequest.cs | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/src/Authentication/Authentication/Cmdlets/InvokeMgGraphRequest.cs b/src/Authentication/Authentication/Cmdlets/InvokeMgGraphRequest.cs index 3edca17967e..f13fb8edd4d 100644 --- a/src/Authentication/Authentication/Cmdlets/InvokeMgGraphRequest.cs +++ b/src/Authentication/Authentication/Cmdlets/InvokeMgGraphRequest.cs @@ -228,6 +228,11 @@ public InvokeMgGraphRequest() internal bool ShouldCheckHttpStatus => !SkipHttpErrorCheck; + /// + /// Only Set Default Content Type (application/json) for POST, PUT and PATCH requests, where its not specified via `-ContentType`. + /// + private bool ShouldSetDefaultContentType => Method == GraphRequestMethod.POST || Method == GraphRequestMethod.PUT || Method == GraphRequestMethod.PATCH; + private static async Task GenerateHttpErrorRecordAsync( HttpMessageFormatter httpResponseMessageFormatter, HttpRequestMessage httpRequestMessage) @@ -606,10 +611,10 @@ private long SetRequestContent(HttpRequestMessage request, string content) Encoding encoding = null; // When contentType is set, coerce to correct encoding. - if (ContentType != null) + if (!string.IsNullOrWhiteSpace(ContentType)) { // If Content-Type contains the encoding format (as CharSet), use this encoding format - // to encode the Body of the WebRequest sent to the server. Default Encoding format + // to encode the Body of the GraphRequest sent to the server. Default Encoding format // would be used if Charset is not supplied in the Content-Type property. try { @@ -661,7 +666,7 @@ private void FillRequestStream(HttpRequestMessage request) { GraphRequestSession.ContentHeaders[HttpKnownHeaderNames.ContentType] = ContentType; } - else if (Method == GraphRequestMethod.POST) + else if (ShouldSetDefaultContentType) { GraphRequestSession.ContentHeaders.TryGetValue(HttpKnownHeaderNames.ContentType, out var contentType); if (string.IsNullOrWhiteSpace(contentType))