Checking if the URL and the request are correct
What's the best way to check if the url and request is correct? For example, after a login redirect, I want to make sure the target url is valid. If not, go to the default page.
We seem to have a problem with the querystring starting with "ReturnUrl =" is duplicated and throws an exception. We would prefer it to go to the default page.
a source to share
Below is a workaround for too long ReturnUrl
querystring parameter . The point is that in adding a new parameter RedirectUrl
(for example, using a method FormsAuthentication.RedirectToLoginPage
) there was something in the querystring, it would be encoded and assigned to the new parameter RedirectUrl
.
The idea is to remove unnecessary (old parameters ReturnUrl
from the query string). For this I use the Application_EndRequest
in global.asax
and Response.RedirectLocation
property.
So, if the response is redirected and the current url contains a parameter ReturnUrl
, it should be removed from the redirected location (because that doesn't make sense).
// parameter key
private static readonly string ReturnUrlParameter = "ReturnUrl";
protected void Application_EndRequest(object sender, EventArgs e)
{
if (Response.IsRequestBeingRedirected)
{
Uri redirectUrl;
if (Uri.TryCreate(Response.RedirectLocation, UriKind.RelativeOrAbsolute, out redirectUrl))
{
redirectUrl = MakeAbsoluteUriIfNecessary(redirectUrl);
Uri currentUrl = Request.Url;
var currentQueryParameters =
HttpUtility.ParseQueryString(HttpUtility.UrlDecode(currentUrl.Query));
// the parameter is present in the current url already
if (currentQueryParameters[ReturnUrlParameter] != null)
{
UriBuilder builder = new UriBuilder(redirectUrl);
builder.Query =
HttpUtility.UrlDecode(builder.Query)
.Replace(Request.Url.Query, string.Empty).TrimStart('?');
Response.RedirectLocation =
Request.Url.MakeRelativeUri(builder.Uri).ToString();
}
}
}
}
private Uri MakeAbsoluteUriIfNecessary(Uri url)
{
if (url.IsAbsoluteUri)
{
return url;
}
else
{
Uri currentUrl = Request.Url;
UriBuilder builder = new UriBuilder(
currentUrl.Scheme,
currentUrl.Host,
currentUrl.Port
);
return new Uri(builder.Uri, url);
}
}
For parsing and URL building, System.Uri
would be the best choice.
A URI is a compact representation of a resource available to your application on the intranet or the Internet. The Uri class defines properties and methods for handling URIs, including parsing, comparison, and union. The Uri class properties are read-only; to create a modifiable object, use the UriBuilder class.
a source to share