2020using System . Text ;
2121using System . Threading ;
2222using System . Threading . Tasks ;
23+ using System . Web ;
2324using static Microsoft . Graph . PowerShell . Authentication . Helpers . AsyncHelpers ;
2425using DriveNotFoundException = System . Management . Automation . DriveNotFoundException ;
2526
@@ -294,6 +295,7 @@ private async Task ReportResponseStatusASync(HttpMessageFormatter responseMessag
294295 /// <returns></returns>
295296 private HttpRequestMessage GetRequest ( HttpClient httpClient , Uri uri )
296297 {
298+
297299 var requestUri = PrepareUri ( httpClient , uri ) ;
298300 var httpMethod = GetHttpMethod ( Method ) ;
299301 // create the base WebRequest object
@@ -346,7 +348,6 @@ private HttpRequestMessage GetRequest(HttpClient httpClient, Uri uri)
346348 request . Headers . Add ( HttpKnownHeaderNames . UserAgent , GraphRequestSession . UserAgent ) ;
347349 }
348350 }
349-
350351 return request ;
351352 }
352353
@@ -359,6 +360,7 @@ private HttpRequestMessage GetRequest(HttpClient httpClient, Uri uri)
359360 private Uri PrepareUri ( HttpClient httpClient , Uri uri )
360361 {
361362 UriBuilder uriBuilder ;
363+
362364 // For AbsoluteUri such as /beta/groups?$count=true, Get the scheme and host from httpClient
363365 // Then use them to compose a new Url with the URL fragment.
364366 if ( uri . IsAbsoluteUri )
@@ -401,8 +403,31 @@ private Uri PrepareUri(HttpClient httpClient, Uri uri)
401403 // set body to null to prevent later FillRequestStream
402404 Body = null ;
403405 }
406+ return EscapeDataStrings ( uriBuilder . Uri ) ;
407+ }
404408
405- return uriBuilder . Uri ;
409+ /// <summary>
410+ /// Escape data string/url encode Uris that have paths containing special characters like #.
411+ /// For a path like /beta/users/first.last_foo.com#EXT#@contoso.onmicrosoft.com, the last segment contains special characters that need to be escaped
412+ /// </summary>
413+ /// <param name="uri"></param>
414+ /// <returns></returns>
415+ private Uri EscapeDataStrings ( Uri uri )
416+ {
417+ int counter = 0 ;
418+ var pathSegments = uri . OriginalString . Split ( '/' ) ;
419+ StringBuilder sb = new StringBuilder ( ) ;
420+ foreach ( var segment in pathSegments )
421+ {
422+ //Skips the left part of the uri i.e https://graph.microsoft.com
423+ if ( counter > 2 )
424+ {
425+ sb . Append ( "/" + Uri . EscapeDataString ( segment ) ) ;
426+ }
427+ counter ++ ;
428+ }
429+ Uri escapedUri = new Uri ( uri . GetLeftPart ( UriPartial . Authority ) + sb . ToString ( ) ) ;
430+ return escapedUri ;
406431 }
407432
408433 private void ThrowIfError ( ErrorRecord error )
0 commit comments