How to get Url Referrer in ASP.NET Core

By Tan Lee Published on Dec 27, 2024  1.43K
In ASP.NET Core, the referrer URL (the page that made the request) can be retrieved from the `Request.Headers` collection, where it is stored under the `Referer` header.

The StringValues class in ASP.NET Core is used to efficiently represent strings, particularly in the HttpContext object. To convert a StringValues instance to a regular string, you can simply call its ToString() method.

using Microsoft.AspNetCore.Mvc;

public class HomeController : Controller
{
    public IActionResult Index()
    {
        // Get the Referer (Referrer) header from the request
        var referrer = Request.Headers["Referer"].ToString();
        
        // Use the referrer URL as needed
        ViewData["Referrer"] = referrer;

        return View();
    }
}

The Referer header is optional. If the request doesn't include it (for example, when a user navigates directly to a page or if it has been stripped out for privacy reasons), the value will be an empty string.