向 HtmlWeb 添加函数 class

Adding functions to HtmlWeb class

我想向 HtmlWeb 添加一些功能 class,特别是这些:

public HtmlDocument SubmitFormValues (NameValueCollection fv, string url)
{
    // Attach a temporary delegate to handle attaching
    // the post back data
    PreRequestHandler handler = delegate(HttpWebRequest request) {
        string payload = this.AssemblePostPayload (fv);
            byte[] buff = Encoding.ASCII.GetBytes (payload.ToCharArray ());
            request.ContentLength = buff.Length;
            request.ContentType = "application/x-www-form-urlencoded";
            System.IO.Stream reqStream = request.GetRequestStream ();
            reqStream.Write (buff, 0, buff.Length);
            return true;
    }
    this.PreRequest += handler;
    HtmlDocument doc = this.Load (url, "POST");
    this.PreRequest -= handler;
    return doc;
}

private string AssemblePostPayload (NameValueCollection fv)
{
    StringBuilder sb = new StringBuilder ();
    foreach (String key in fv.AllKeys) {
        sb.Append ("&" + key + "=" + fv.Get (key));
    }
    return sb.ToString ().Substring (1);
}

这些函数用于POST数据到网站,然后得到响应html。

我在添加这些功能时遇到了一些困难,我想知道如何正确地添加这些功能。

该函数可以这样使用:

HtmlWeb webGet = new HtmlWeb();
NameValueCollection postData = new NameValueCollection (1);
postData.Add ("name", "value");
string url = "url";
HtmlDocument doc = webGet.SubmitFormValues (postData, url);

假设您的方法是正确的,您可以创建自己的 class 继承 HtmlWeb 并将 2 个方法放在那里:

public class HtmlWebExtended : HtmlWeb
{
    public HtmlDocument SubmitFormValues(NameValueCollection fv, string url)
    {
        // Attach a temporary delegate to handle attaching
        // the post back data
        ......
    }

    private string AssemblePostPayload(NameValueCollection fv)
    {
        ......
    }
}

然后使用您自己的 HtmlWebExtended class 而不是预定义的 HtmlWeb :

HtmlWebExtended webGet = new HtmlWebExtended();
NameValueCollection postData = new NameValueCollection (1);
postData.Add("name", "value");
string url = "url";
HtmlDocument doc = webGet.SubmitFormValues(postData, url);