How do I get the referrer URL in an ASP.NET MVC action?

asp.net MvcRedirectReferrer

asp.net Mvc Problem Overview


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.

asp.net Mvc Solutions


Solution 1 - asp.net Mvc

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

Solution 2 - asp.net Mvc

Request.ServerVariables["http_referer"]

Should do.

Solution 3 - asp.net Mvc

You can use this

filterContext.RequestContext.HttpContext.Request.UrlReferrer.AbsolutePath

Solution 4 - asp.net Mvc

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRyallView Question on Stackoverflow
Solution 1 - asp.net Mvcderek lawlessView Answer on Stackoverflow
Solution 2 - asp.net MvcDaniel ElliottView Answer on Stackoverflow
Solution 3 - asp.net MvcNavish RampalView Answer on Stackoverflow
Solution 4 - asp.net MvcAndrey BurykinView Answer on Stackoverflow