2
2
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
3
3
4
4
using System ;
5
+ using System . Text ;
5
6
6
7
namespace Microsoft . AspNet . Http . Extensions
7
8
{
@@ -10,6 +11,8 @@ namespace Microsoft.AspNet.Http.Extensions
10
11
/// </summary>
11
12
public static class UriHelper
12
13
{
14
+ private const string SchemeDelimiter = "://" ;
15
+
13
16
/// <summary>
14
17
/// Combines the given URI components into a string that is properly encoded for use in HTTP headers.
15
18
/// </summary>
@@ -47,8 +50,24 @@ public static string Encode(
47
50
QueryString query = new QueryString ( ) ,
48
51
FragmentString fragment = new FragmentString ( ) )
49
52
{
50
- string combinePath = ( pathBase . HasValue || path . HasValue ) ? ( pathBase + path ) . ToString ( ) : "/" ;
51
- return $ "{ scheme } ://{ host . ToString ( ) } { combinePath } { query . ToString ( ) } { fragment . ToString ( ) } ";
53
+ var combinedPath = ( pathBase . HasValue || path . HasValue ) ? ( pathBase + path ) . ToString ( ) : "/" ;
54
+
55
+ var encodedHost = host . ToString ( ) ;
56
+ var encodedQuery = query . ToString ( ) ;
57
+ var encodedFragment = fragment . ToString ( ) ;
58
+
59
+ // PERF: Calculate string length to allocate correct buffer size for StringBuilder.
60
+ var length = scheme . Length + SchemeDelimiter . Length + encodedHost . Length
61
+ + combinedPath . Length + encodedQuery . Length + encodedFragment . Length ;
62
+
63
+ return new StringBuilder ( length )
64
+ . Append ( scheme )
65
+ . Append ( SchemeDelimiter )
66
+ . Append ( encodedHost )
67
+ . Append ( combinedPath )
68
+ . Append ( encodedQuery )
69
+ . Append ( encodedFragment )
70
+ . ToString ( ) ;
52
71
}
53
72
54
73
/// <summary>
@@ -93,7 +112,23 @@ public static string GetEncodedUrl(this HttpRequest request)
93
112
/// <returns></returns>
94
113
public static string GetDisplayUrl ( this HttpRequest request )
95
114
{
96
- return request . Scheme + "://" + request . Host . Value + request . PathBase . Value + request . Path . Value + request . QueryString . Value ;
115
+ var host = request . Host . Value ;
116
+ var pathBase = request . PathBase . Value ;
117
+ var path = request . Path . Value ;
118
+ var queryString = request . QueryString . Value ;
119
+
120
+ // PERF: Calculate string length to allocate correct buffer size for StringBuilder.
121
+ var length = request . Scheme . Length + SchemeDelimiter . Length + host . Length
122
+ + pathBase . Length + path . Length + queryString . Length ;
123
+
124
+ return new StringBuilder ( length )
125
+ . Append ( request . Scheme )
126
+ . Append ( SchemeDelimiter )
127
+ . Append ( host )
128
+ . Append ( pathBase )
129
+ . Append ( path )
130
+ . Append ( queryString )
131
+ . ToString ( ) ;
97
132
}
98
133
}
99
- }
134
+ }
0 commit comments