Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get Url Referrer in ASP.NET Core MVC?

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();

As of asp.net core 2 use GetTypedHeaders

RequestHeaders header = request.GetTypedHeaders();
Uri uriReferer = header.Referer;

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());
}

Here is how I got url referrer:-

@{
string referer = Context.Request.Headers["Referer"].ToString();
Uri baseUri = new Uri(referer);}


<form asp-action="Login" asp-route-returnUrl="@baseUri.AbsolutePath">

using Microsoft.AspNetCore.Server.Kestrel.Internal.Http;

var referer = ((FrameRequestHeaders)Request.Headers).HeaderReferer.FirstOrDefault();

almost the same as the accepted answer without the magic string