[c#] Getting the HTTP Referrer in ASP.NET

I'm looking for a quick, easy and reliable way of getting the browser's HTTP Referrer in ASP.Net (C#). I know the HTTP Referrer itself is unreliable, but I do want a reliable way of getting the referrer if it is present.

This question is related to c# asp.net http http-headers http-referer

The answer is


Request.Headers["Referer"]

Explanation

The Request.UrlReferer property will throw a System.UriFormatException if the referer HTTP header is malformed (which can happen since it is not usually under your control).

Therefore, the Request.UrlReferer property is not 100% reliable - it may contain data that cannot be parsed into a Uri class. To ensure the value is always readable, use Request.Headers["Referrer"] instead.

As for using Request.ServerVariables as others here have suggested, per MSDN:

Request.ServerVariables Collection

The ServerVariables collection retrieves the values of predetermined environment variables and request header information.

Request.Headers Property

Gets a collection of HTTP headers.

Request.Headers is a better choice than Request.ServerVariables, since Request.ServerVariables contains all of the environment variables as well as the headers, where Request.Headers is a much shorter list that only contains the headers.

So the most reliable solution is to use the Request.Headers collection to read the value directly. Do heed Microsoft's warnings about HTML encoding the value if you are going to display it on a form, though.


Like this: HttpRequest.UrlReferrer Property

Uri myReferrer = Request.UrlReferrer;
string actual = myReferrer.ToString();

Since Google takes you to this post when searching for C# Web API Referrer here's the deal: Web API uses a different type of Request from normal MVC Request called HttpRequestMessage which does not include UrlReferrer. Since a normal Web API request does not include this information, if you really need it, you must have your clients go out of their way to include it. Although you could make this be part of your API Object, a better way is to use Headers.

First, you can extend HttpRequestMessage to provide a UrlReferrer() method:

public static string UrlReferrer(this HttpRequestMessage request)
{
    return request.Headers.Referrer == null ? "unknown" : request.Headers.Referrer.AbsoluteUri;
}

Then your clients need to set the Referrer Header to their API Request:

// Microsoft.AspNet.WebApi.Client
client.DefaultRequestHeaders.Referrer = new Uri(url);

And now the Web API Request includes the referrer data which you can access like this from your Web API:

Request.UrlReferrer();

Sometime you must to give all the link like this

System.Web.HttpContext.Current.Request.UrlReferrer.ToString();

(in option when "Current" not founded)


Use the Request.UrlReferrer property.

Underneath the scenes it is just checking the ServerVariables("HTTP_REFERER") property.


Belonging to other reply, I have added condition clause for getting null.

string ComingUrl = "";
if (Request.UrlReferrer != null)
{
    ComingUrl = System.Web.HttpContext.Current.Request.UrlReferrer.ToString();
}
else
{
    ComingUrl = "Direct"; // Your code
}

I'm using .Net Core 2 mvc, this one work for me ( to get the previews page) :

HttpContext.Request.Headers["Referer"];

string referrer = HttpContext.Current.Request.UrlReferrer.ToString();

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to asp.net

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to http

Access blocked by CORS policy: Response to preflight request doesn't pass access control check Axios Delete request with body and headers? Read response headers from API response - Angular 5 + TypeScript Android 8: Cleartext HTTP traffic not permitted Angular 4 HttpClient Query Parameters Load json from local file with http.get() in angular 2 Angular 2: How to access an HTTP response body? What is HTTP "Host" header? Golang read request body Angular 2 - Checking for server errors from subscribe

Examples related to http-headers

Set cookies for cross origin requests Adding a HTTP header to the Angular HttpClient doesn't send the header, why? Passing headers with axios POST request What is HTTP "Host" header? CORS error :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response Using Axios GET with Authorization Header in React-Native App Axios get access to response header fields Custom header to HttpClient request Send multipart/form-data files with angular using $http Best HTTP Authorization header type for JWT

Examples related to http-referer

In what cases will HTTP_REFERER be empty Getting the HTTP Referrer in ASP.NET Get original URL referer with PHP? Determining Referer in PHP