92

How do I get the referrer URL in an ASP.NET MVC action? I am trying to redirect back to the page before you called an action.

tereško
  • 57,247
  • 24
  • 95
  • 149
Ryall
  • 11,669
  • 11
  • 50
  • 75
  • 5
    Bear in mind that not all user-agents (AKA browsers) will send the referrer information, and some may even fake it. – belugabob Sep 24 '09 at 16:36

4 Answers4

152

You can use Request.UrlReferrer to get the referring URL as well if you don't like accessing the Request.ServerVariables dictionary directly.

derek lawless
  • 2,534
  • 2
  • 16
  • 13
  • It is exactly what I need. Thank you, bro! – NoWar Sep 23 '16 at 12:12
  • `Request.UrlReferrer` is actually the URI but from there you can get everything you need regarding the referrer URL. (More about URI vs URL: https://stackoverflow.com/questions/176264/what-is-the-difference-between-a-uri-a-url-and-a-urn). – Miguel Feb 01 '19 at 19:57
20
Request.ServerVariables["http_referer"]

Should do.

demonplus
  • 5,320
  • 11
  • 48
  • 64
Daniel Elliott
  • 22,229
  • 10
  • 62
  • 82
9

You can use this

filterContext.RequestContext.HttpContext.Request.UrlReferrer.AbsolutePath
Elzo Valugi
  • 25,880
  • 14
  • 91
  • 114
Navish Rampal
  • 482
  • 1
  • 5
  • 8
4

You can pass referrer url to viewModel, in my opinion it's better approach than sharing via the state, try so:

public interface IReferrer
{
    String Referrer { get; set; }
}

...

public static MvcHtmlString HiddenForReferrer<TModel>(this HtmlHelper<TModel> htmlHelper) where TModel : IReferrer
{
    var str = htmlHelper.HiddenFor(hh => hh.Referrer);
    var referrer = HttpContext.Current.Request.UrlReferrer.AbsoluteUri;
    return new MvcHtmlString(str.ToHtmlString().Replace("value=\"\"", String.Format("value=\"{0}\"", referrer)));
}

...

@Html.HiddenForReferrer()
Andrey Burykin
  • 642
  • 10
  • 23
  • 1
    huh, never realized underscore by itself is a valid variable name. How 'bout that. – BVernon Feb 04 '18 at 02:58
  • @BVernon The real question is why anyone would use it that way. The only convention I am aware of with a single underscore for a name is to signify that it's just a placeholder for a variable you don't want or need. – Daniel Dec 10 '19 at 19:10
  • @Daniel I agree, fixed – Andrey Burykin May 21 '20 at 09:05