How to set referrer to HtmlWeb in HtmlAgilityPack

c# html-agility-pack

Question

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;
    }

Accepted Answer

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



Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow