I want to assign a dynamic (meaning the referrer changes according to the request URL.
I cannot find a Referrer
or Headers
property. All I can see is PreRequest
, to which I can add a handler. Is there any other way to pass a referrer to the handler without using a global variable?
void SomeMethod()
{
....
var referrer = "some URL";
//web.Referrer = referrer; Ideal way, but not possible
web.PreRequest += OnPreRequest;
....
}
bool OnPreRequest(HttpWebRequest req)
{
req.Referer = ??; //how to know the referrer address here?
return false;
}
Is there any other way to pass a referrer to the handler without using a global variable?
You can use captured variables. See, for ex, this link "Understanding Variable Capturing in C#" or this Closures and Captured Variable C#
Now you can do
void SomeMethod()
{
var referrer = "some URL";
web.PreRequest += (req){
req.Referer = referrer;
return false;
};
}
Some notes:
What are closures?
Closures are function which can be stored in a variable, passed around as parameter and refer to the variables visible at the time they are defined.
Captured Variable
Outer variable referenced by the closure is called captured variable