How to get the previous url in a MasterPage in C# ?
I'm trying to find the page which is redirected from.
Thanks in advance.
How to get the previous url in a MasterPage in C# ?
I'm trying to find the page which is redirected from.
Thanks in advance.
You can get information of the previous url with the UrlReferrer
property. This works in MVC and Web forms.
Request.UrlReferrer.AbsoluteUri
Note that in the first page the property Request.UrlReferrer
will be null. Also, it will be null if a redirection occurs (e.g. when a user logs into the web page).
This property is based on the HTTP_REFERER variable, so you could use this one instead.
Request.ServerVariables["HTTP_REFERER"]
Since the HTTP_REFERER is a variable sent by the client it might be altered or removed by the request. Also, the variable is not set when the referre url starts with https
.
This article mentions a few points why the Request.UrlReferrer
can be null.
if(Request.UrlReferrer != null) {...}
default1.aspx
and clicks a links to the page default2.aspx
Usually you use a query string parameter to achieve this: current?previousUrl=/some/11
.
This will allow you to access this value from the server-side code using Context.Request.QueryString["previousUrl"]
in your master page code-behind.
As of .NET 6.0 the UrlReferrer object is deprecated from the Request (HttpRequest) object. It is now stored as a part of the Request.Headers dictionary.
The new way to access the UrlReffer object would be:
string urlReferrer = Request.Headers["Referer"]!.ToString();
Note: this object may be null in certain cases. It would be most safe to first check if the object is null before accessing it.
string? urlReferrer = null;
if (Request.Headers.ContainsKey("Referer"))
{
urlReferrer = Request.Headers["Referer"]!.ToString();
}