Getting the HTTP Referrer in ASP.NET

2019-01-01 09:12发布

I'm looking for a quick, easy and reliable way of getting the browser's HTTP Referrer in ASP.Net (C#). I know the HTTP Referrer itself is unreliable, but I do want a reliable way of getting the referrer if it is present.

8条回答
泪湿衣
2楼-- · 2019-01-01 09:37

Sometime you must to give all the link like this

System.Web.HttpContext.Current.Request.UrlReferrer.ToString();

(in option when "Current" not founded)

查看更多
妖精总统
3楼-- · 2019-01-01 09:45

You could use the UrlReferrer property of the current request:

Request.UrlReferrer

This will read the Referer HTTP header from the request which may or may not be supplied by the client (user agent).

查看更多
泛滥B
4楼-- · 2019-01-01 09:46

Like this: HttpRequest.UrlReferrer Property

Uri myReferrer = Request.UrlReferrer;
string actual = myReferrer.ToString();
查看更多
像晚风撩人
5楼-- · 2019-01-01 09:47

Use the Request.UrlReferrer property.

Underneath the scenes it is just checking the ServerVariables("HTTP_REFERER") property.

查看更多
余欢
6楼-- · 2019-01-01 09:47
Request.Headers["Referer"]

Explanation

The Request.UrlReferer will throw a System.UriFormatException if the referer HTTP header is malformed (which can happen since it is not usually under your control).

As for using Request.ServerVariables, per MSDN:

Request.ServerVariables Collection

The ServerVariables collection retrieves the values of predetermined environment variables and request header information.

Request.Headers Property

Gets a collection of HTTP headers.

Request.Headers is a better choice than Request.ServerVariables, since Request.ServerVariables contains all of the environment variables as well as the headers, where Request.Headers is a much shorter list that only contains the headers.

So the best solution is to use the Request.Headers collection to read the value directly. Do heed Microsoft's warnings about HTML encoding the value if you are going to display it on a form, though.

查看更多
余生无你
7楼-- · 2019-01-01 09:48
string referrer = HttpContext.Current.Request.UrlReferrer.ToString();
查看更多
登录 后发表回答