如何使 WebClient 对象保持活动状态以避免 C# 中的会话过期

How to keep alive a WebClient object to avoid session expiration in C#

你能帮我解决这个问题吗,我在VS2019中有一个windows表单,我想在发送验证码和其他参数(2个参数)后生成html,我的windows 表单包含 devexpress 控件,我加载验证码的图片编辑,我放置验证码的 textedit1,我放置第二个参数(例如 06892898)的 textedit2,我单击以将验证码加载到图片编辑的 simplebutton1 ,使用 2 个参数请求网站的 simplebutton2,问题是当我在 url 中传递两个参数时,我得到一个 html 消息“会话已完成”,如何我可以获取会话或使 C# 中的 webclient 对象保持活动状态吗?提前致谢,这是我的代码:

private WebClient myClient = new WebClient();
public FrmData()
{
    InitializeComponent();
}
private void btnCaptcha_Click(object sender, EventArgs e)
{
    myClient.DownloadFile(new Uri("http://ww4.essalud.gob.pe:7777/acredita/captcha.jpg"), @"c:\temp\captcha.jpg");
    pictureCaptcha.Image = Image.FromFile(@"c:\temp\captcha.jpg");
}
private void btnLoad_Click(object sender, EventArgs e)
{
    string line = string.Empty;
    try
    {
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://ww4.essalud.gob.pe:7777/acredita/servlet/Ctrlwacre?captchafield_doc=" + txtedit1.Text + "&td=1&nd=" + txtedit2.Text);
        HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
        StreamReader sr = new StreamReader(resp.GetResponseStream(), System.Text.Encoding.UTF8);
        line = sr.ReadToEnd();
        sr.Close();
        resp.Close();
        XtraMessageBox.Show("" + line);
    }
    catch (Exception ex)
    {
        XtraMessageBox.Show("" + ex.Message);
    }
}

我使用 HttpWebRequest、HttpWebResponse、CookieContainer class 获得了解决方案,我做了以下代码:

private HttpWebRequest request;
private HttpWebResponse response;
private CookieContainer cookies = new CookieContainer();
private void btnCaptcha_Click(object sender, EventArgs e)
{
    try
    {
        request = (HttpWebRequest)WebRequest.Create("http://ww4.essalud.gob.pe:7777/acredita/captcha.jpg");
        request.CookieContainer = cookies;
        request.Timeout = 10000;
        request.ReadWriteTimeout = 10000;
        request.KeepAlive = true;
        response = (HttpWebResponse)request.GetResponse();
        pictureCaptcha.Image = Image.FromStream(response.GetResponseStream());
    }
    catch (Exception ex)
    {
        XtraMessageBox.Show("" + ex.Message);
    }
}
private void btnLoad_Click(object sender, EventArgs e)
{
    string line = string.Empty;
    try
    {
        request = (HttpWebRequest)WebRequest.Create("http://ww4.essalud.gob.pe:7777/acredita/servlet/Ctrlwacre?captchafield_doc=" + txtCaptcha.Text + "&td=1&nd=06915398");
        request.CookieContainer = cookies;
        response = (HttpWebResponse)request.GetResponse();
        StreamReader sr = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8);
        line = sr.ReadToEnd();
        sr.Close();
        response.Close();
    }
    catch (Exception ex)
    {
        XtraMessageBox.Show("" + ex.Message);
    }
    XtraMessageBox.Show("" + line);
}

感谢所有评论和使用 cookie 并保持活力的想法。