@@ -66,10 +66,10 @@ public static string BuildAbsolute(
6666 PathString path = default ,
6767 QueryString query = default )
6868 {
69- string hostText = host . ToString ( ) ;
70- string pathBaseText = pathBase . ToString ( ) ;
71- string pathText = path . ToString ( ) ;
72- string queryText = query . ToString ( ) ;
69+ string hostText = host . ToUriComponent ( ) ;
70+ string pathBaseText = pathBase . ToUriComponent ( ) ;
71+ string pathText = path . ToUriComponent ( ) ;
72+ string queryText = query . ToUriComponent ( ) ;
7373
7474 // PERF: Calculate string length to allocate correct buffer size for string.Create.
7575 int length =
@@ -97,6 +97,46 @@ public static string BuildAbsolute(
9797 return string . Create ( length , ( handling == CaseHandling . LowerInvariant , hostText , pathBaseText , pathText , queryText ) , InitializeAbsoluteUriStringSpanAction ) ;
9898 }
9999
100+ /// <summary>
101+ /// Generates a string from the given absolute or relative Uri that is appropriately encoded for use in
102+ /// HTTP headers. Note that a unicode host name will be encoded as punycode.
103+ /// </summary>
104+ /// <param name="handling">Determines case handling for the result.</param>
105+ /// <param name="uri">The Uri to encode.</param>
106+ /// <returns>The encoded string version of <paramref name="uri"/>.</returns>
107+ public static string Encode ( CaseHandling handling , string uri )
108+ => Encode ( handling , new Uri ( uri , UriKind . RelativeOrAbsolute ) ) ;
109+
110+ /// <summary>
111+ /// Generates a string from the given absolute or relative Uri that is appropriately encoded for use in
112+ /// HTTP headers. Note that a unicode host name will be encoded as punycode.
113+ /// </summary>
114+ /// <param name="handling">Determines case handling for the result.</param>
115+ /// <param name="uri">The Uri to encode.</param>
116+ /// <returns>The encoded string version of <paramref name="uri"/>.</returns>
117+ public static string Encode ( CaseHandling handling , Uri uri )
118+ {
119+ Guard . NotNull ( uri , nameof ( uri ) ) ;
120+ if ( uri . IsAbsoluteUri )
121+ {
122+ return BuildAbsolute (
123+ handling ,
124+ host : HostString . FromUriComponent ( uri ) ,
125+ pathBase : PathString . FromUriComponent ( uri ) ,
126+ query : QueryString . FromUriComponent ( uri ) ) ;
127+ }
128+ else
129+ {
130+ string components = uri . GetComponents ( UriComponents . SerializationInfoString , UriFormat . UriEscaped ) ;
131+ if ( handling == CaseHandling . LowerInvariant )
132+ {
133+ return components . ToLowerInvariant ( ) ;
134+ }
135+
136+ return components ;
137+ }
138+ }
139+
100140 /// <summary>
101141 /// Copies the specified <paramref name="text"/> to the specified <paramref name="buffer"/> starting at the specified <paramref name="index"/>.
102142 /// </summary>
0 commit comments