Ryall
Ryall

Reputation: 12281

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

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.

Upvotes: 94

Views: 95537

Answers (4)

Andrey Burykin
Andrey Burykin

Reputation: 728

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

Upvotes: 4

Daniel Elliott
Daniel Elliott

Reputation: 22857

Request.ServerVariables["http_referer"]

Should do.

Upvotes: 20

Navish Rampal
Navish Rampal

Reputation: 482

You can use this

filterContext.RequestContext.HttpContext.Request.UrlReferrer.AbsolutePath

Upvotes: 9

derek lawless
derek lawless

Reputation: 2564

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

Upvotes: 155

Related Questions