How can I get Url Referrer in ASP.NET Core MVC?
As of asp.net core 2 use GetTypedHeaders
RequestHeaders header = request.GetTypedHeaders();
Uri uriReferer = header.Referer;
You're almost there. The StringValues
class is just a type ASP.NET uses to efficiently represent strings in the framework. Especially in the HttpContext
object. You can just call ToString()
on it to convert it to a string:
string referer = Request.Headers["Referer"].ToString();
This works (tested in .NET Core 3.1):
Request.GetTypedHeaders().Referer
Request
is a property of both ControllerBase
(and therefore Controller
too) and HttpContext
, so you can get it from either.
For example, to redirect to the referring page from a controller action, just do this:
public IActionResult SomeAction()
{
return Redirect(Request.GetTypedHeaders().Referer.ToString());
}