summaryrefslogtreecommitdiffstats
path: root/src/DotNetOpenAuth.AspNet/UriHelper.cs
blob: 2c6e5a996ebdee673b85110b85fcffb6ba00aab3 (plain)
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
76
77
78
79
80
81
82
83
84
85
//-----------------------------------------------------------------------
// <copyright file="UriHelper.cs" company="Microsoft">
//     Copyright (c) Microsoft. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------

namespace DotNetOpenAuth.AspNet {
	using System;
	using System.Text.RegularExpressions;
	using System.Web;
	using DotNetOpenAuth.Messaging;

	/// <summary>
	/// The uri helper.
	/// </summary>
	internal static class UriHelper {
		#region Public Methods and Operators

		/// <summary>
		/// The attach query string parameter.
		/// </summary>
		/// <param name="url">
		/// The url.
		/// </param>
		/// <param name="parameterName">
		/// The parameter name.
		/// </param>
		/// <param name="parameterValue">
		/// The parameter value.
		/// </param>
		/// <returns>
		/// </returns>
		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>
		/// <param name="context">
		/// The context.
		/// </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 = context.Request.GetPublicFacingUrl();
			return new Uri(publicUrl, returnUrl);
		}

		#endregion
	}
}