1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
|
using System;
using System.Text.RegularExpressions;
using System.Web;
using DotNetOpenAuth.Messaging;
namespace DotNetOpenAuth.AspNet
{
internal static class UriHelper
{
/// <summary>
/// Attaches the query string '__provider' to an existing url. If the url already
/// contains the __provider query string, it overrides it with the specified provider name.
/// </summary>
/// <param name="url">The original url.</param>
/// <param name="providerName">Name of the provider.</param>
/// <returns>The new url with the provider name query string attached</returns>
/// <example>
/// If the url is: http://contoso.com, and providerName='facebook', the returned value is: http://contoso.com?__provider=facebook
/// If the url is: http://contoso.com?a=1, and providerName='twitter', the returned value is: http://contoso.com?a=1&__provider=twitter
/// If the url is: http://contoso.com?a=1&__provider=twitter, and providerName='linkedin', the returned value is: http://contoso.com?a=1&__provider=linkedin
/// </example>
/// <remarks>
/// The reason we have to do this is so that when the external service provider forwards user
/// back to our site, we know which provider it comes back from.
/// </remarks>
public static Uri AttachQueryStringParameter(this Uri url, string parameterName, string parameterValue)
{
UriBuilder builder = new UriBuilder(url);
string query = builder.Query;
if (query.Length > 1)
{
// remove the '?' character in front of the query string
query = query.Substring(1);
}
string parameterPrefix = parameterName + "=";
string encodedParameterValue = Uri.EscapeDataString(parameterValue);
string newQuery = Regex.Replace(query, parameterPrefix + "[^\\&]*", parameterPrefix + encodedParameterValue);
if (newQuery == query)
{
if (newQuery.Length > 0)
{
newQuery += "&";
}
newQuery = newQuery + parameterPrefix + encodedParameterValue;
}
builder.Query = newQuery;
return builder.Uri;
}
/// <summary>
/// Converts an app-relative url, e.g. ~/Content/Return.cshtml, to a full-blown url, e.g. http://mysite.com/Content/Return.cshtml
/// </summary>
/// <param name="returnUrl">The return URL.</param>
/// <returns></returns>
public static Uri ConvertToAbsoluteUri(string returnUrl, HttpContextBase context)
{
if (Uri.IsWellFormedUriString(returnUrl, UriKind.Absolute))
{
return new Uri(returnUrl, UriKind.Absolute);
}
if (!VirtualPathUtility.IsAbsolute(returnUrl))
{
returnUrl = VirtualPathUtility.ToAbsolute(returnUrl);
}
Uri publicUrl = HttpRequestInfo.GetPublicFacingUrl(context.Request, context.Request.ServerVariables);
return new Uri(publicUrl, returnUrl);
}
}
}
|