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.
            Asked
            
        
        
            Active
            
        
            Viewed 9.3k times
        
    92
            
            
        - 
                    5Bear 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 Answers
153
            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,544
- 2
- 16
- 13
- 
                    
- 
                    `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,613
- 12
- 49
- 68
 
    
    
        Daniel Elliott
        
- 22,647
- 10
- 64
- 82
9
            
            
        You can use this
filterContext.RequestContext.HttpContext.Request.UrlReferrer.AbsolutePath
 
    
    
        Elzo Valugi
        
- 27,240
- 15
- 95
- 114
 
    
    
        Navish Rampal
        
- 482
- 1
- 5
- 9
- 
                    2This would work in a filter context, but not in the action context as the question asked for. – Jace Rhea Aug 30 '13 at 15:19
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
        
- 700
- 11
- 23
- 
                    1huh, never realized underscore by itself is a valid variable name. How 'bout that. – BVernon Feb 04 '18 at 02:58
- 
                    1@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
- 
                    
 
    