The reason why HttpContext.Current.Request.Headers.Keys["CustomeUrl"].ToString()
is always null in your controller is because you are adding the header to HttpContext.Current.Response
in your view and reading it from HttpContext.Current.Request
in your controller. Since the view and controller both execute on the server and share the same Request/Response model, you need to read it from the same location that you write it.
That said, since both the View and Controller have access to the same Request/Response data. There is no need to pass a value that already exists in HTTP context to the controller because it already has it. Also, the UrlReferrer
property will throw an exception if the URL is malformed (which can happen since it is not usually under your direct control). Therefore, you should use the Request.Headers
collection to retrieve it. Therefore, this line will work the same in your controller and view.
string referrer = HttpContext.Request.Headers["Referer"];
Side Note: You shouldn't use the legacy static HttpContext.Current accessor in MVC because there is no way to abstract it (and therefore it may be different from what is available in HttpContextBase
if you are using custom or 3rd party components that change it).
HTTP referer is only non-null if a hyperlink is clicked on in the browser that takes you to the URL of the MVC application.
Page A
hosted at: http://example.com/page-a.html
<html>
<head></head>
<body>
<a href="http://example2.com/page-b">click me</a>
</body>
Page B (MVC)
hosted at: http://example2.com/page-b
var referrer = HttpContext.Request.Headers["Referer"];
// referrer value is http://example.com/page-a.html if the above
// hyperlink is clicked on page-a.html. If the user types the
// new URL in the browser instead of clicking the hyperlink,
// HTTP referer will usually be null, depending on the browser implementation.
NOTE: HTTP referer is completely dependent upon the client and any firewalls that exist between the client and server. Some firewalls can strip headers out so applications should not rely on them in order to function (or at the very least have a fallback plan in case the header is not available). This information should generally only be used for tracking/debugging purposes.