在异步 Web 请求失败中设置请求属性。 C#

发布于 2024-12-23 06:55:08 字数 3276 浏览 0 评论 0原文

private void LoginButton_Click(object sender, EventArgs e)
{
    try
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(loginUrl);
        IAsyncResult result = request.BeginGetResponse(
            new AsyncCallback(DeleResponse), request);
    }
    catch(Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

这是调用按钮单击事件的方法

private void DeleResponse(IAsyncResult result)
{
    byte[] PostData = Encoding.UTF8.GetBytes("username=" + userInp.Text + "&password=" + passInp.Text + extraLoginPostString);
    LoginButton.Text = "Logging in...";
    LoginButton.Enabled = false;
    HttpWebRequest request = (HttpWebRequest)result.AsyncState;
    request.Method = "Post";
    request.CookieContainer = authCookie;
    request.ContentType = "application/x-www-form-urlencoded";
    request.AllowAutoRedirect = false;
    postWriter = request.GetRequestStream();
    postWriter.Write(PostData, 0, PostData.Length);
    postWriter.Close();
        HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);
        string serverData = new StreamReader(response.GetResponseStream()).ReadToEnd();
    string loginValidateString = response.GetResponseHeader(loginValidateStringHolder);
    if (loginValidateString.Contains(LoggedKeyword))
    { 
            some process here:
        }
        else if( FAILKEYWORDCHECK HERE)
        {
            login page process here;
        }
    }

问题是当我用 fiddler 检查它时我只能看到以下标头属性。

Connection: Keep-Alive;
Host: www.example.com

我无法在请求标头中设置属性的原因是什么?

编辑:添加了我已经实现的同步请求方法,没有任何错误。

 private void LoginButton_Click(object sender, EventArgs e)
    {
        try
        {
           LoginButton.Text = "Logging in...";
            LoginButton.Enabled = false;
            byte[] PostData = Encoding.UTF8.GetBytes("username=" + userInp.Text + "&password=" + passInp.Text + extraLoginPostString);
            request = (HttpWebRequest)WebRequest.Create(loginUrl);
            request.Method = "Post";
            request.CookieContainer = authCookie;
            request.ContentType = "application/x-www-form-urlencoded";
            request.AllowAutoRedirect = false;

            postWriter = request.GetRequestStream();
            postWriter.Write(PostData, 0, PostData.Length);
            postWriter.Close();

            response = (HttpWebResponse)request.GetResponse();

            string serverData = new StreamReader(response.GetResponseStream()).ReadToEnd();
            string loginValidateString = response.GetResponseHeader(loginValidateStringHolder);
            if (loginValidateString.Contains(LoggedKeyword))
            {
                MessageBox.Show("Logged in Successfully");

                foreach (Cookie cookieReader in response.Cookies)
                {
                    authCookie.Add(cookieReader);
                }
                Success method continues..
            }
            else if (loginValidateString.Contains(failedLogKeyword))
            {
                Failed process
            }
        }
        catch
        {
            Catchblock
        }
        }

意味着,我只知道如何为正常请求设置属性。

private void LoginButton_Click(object sender, EventArgs e)
{
    try
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(loginUrl);
        IAsyncResult result = request.BeginGetResponse(
            new AsyncCallback(DeleResponse), request);
    }
    catch(Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

And here is the method which called to on button click event

private void DeleResponse(IAsyncResult result)
{
    byte[] PostData = Encoding.UTF8.GetBytes("username=" + userInp.Text + "&password=" + passInp.Text + extraLoginPostString);
    LoginButton.Text = "Logging in...";
    LoginButton.Enabled = false;
    HttpWebRequest request = (HttpWebRequest)result.AsyncState;
    request.Method = "Post";
    request.CookieContainer = authCookie;
    request.ContentType = "application/x-www-form-urlencoded";
    request.AllowAutoRedirect = false;
    postWriter = request.GetRequestStream();
    postWriter.Write(PostData, 0, PostData.Length);
    postWriter.Close();
        HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);
        string serverData = new StreamReader(response.GetResponseStream()).ReadToEnd();
    string loginValidateString = response.GetResponseHeader(loginValidateStringHolder);
    if (loginValidateString.Contains(LoggedKeyword))
    { 
            some process here:
        }
        else if( FAILKEYWORDCHECK HERE)
        {
            login page process here;
        }
    }

The problem is when I check this with fiddler I can see only following header properties.

Connection: Keep-Alive;
Host: www.example.com

What would be the reason that I can't set properties in the request header?

Edit: Added synchronous request method which I already achieved without any errors.

 private void LoginButton_Click(object sender, EventArgs e)
    {
        try
        {
           LoginButton.Text = "Logging in...";
            LoginButton.Enabled = false;
            byte[] PostData = Encoding.UTF8.GetBytes("username=" + userInp.Text + "&password=" + passInp.Text + extraLoginPostString);
            request = (HttpWebRequest)WebRequest.Create(loginUrl);
            request.Method = "Post";
            request.CookieContainer = authCookie;
            request.ContentType = "application/x-www-form-urlencoded";
            request.AllowAutoRedirect = false;

            postWriter = request.GetRequestStream();
            postWriter.Write(PostData, 0, PostData.Length);
            postWriter.Close();

            response = (HttpWebResponse)request.GetResponse();

            string serverData = new StreamReader(response.GetResponseStream()).ReadToEnd();
            string loginValidateString = response.GetResponseHeader(loginValidateStringHolder);
            if (loginValidateString.Contains(LoggedKeyword))
            {
                MessageBox.Show("Logged in Successfully");

                foreach (Cookie cookieReader in response.Cookies)
                {
                    authCookie.Add(cookieReader);
                }
                Success method continues..
            }
            else if (loginValidateString.Contains(failedLogKeyword))
            {
                Failed process
            }
        }
        catch
        {
            Catchblock
        }
        }

Means, I just know how to set properties for normal requests.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

苍景流年 2024-12-30 06:55:08

响应可用时,您尝试设置请求的属性。您需要在向服务器发出请求之前设置请求属性 - 因此您应该在 LoginButton_Click 中设置它们,而不是在响应处理代码中设置它们。同样,您不能在 BeginGetResponse 的回调中使用 GetRequestStream。粗略地说,您想要:

  • 在初始事件处理程序中:
    • 创建请求
    • 设置简单属性
    • 调用BeginGetRequestStream
  • BeginGetRequestStream 的回调处理程序中
    • 写出正文数据
    • 调用BeginGetResponse
  • BeginGetResponse 的回调处理程序中
    • 处理响应数据

或者,除非您必须使用异步调用,否则您可以创建一个单独的线程并使用同步版本。在 C# 5 提供语言支持之前,这会更简单。

You're trying to set properties of the request when the response is available. You need to set the request properties before you make the request to the server - so you should be setting them in LoginButton_Click, not in the response handling code. Likewise you can't use GetRequestStream in a callback for BeginGetResponse. Roughly speaking, you want:

  • In the initial event handler:
    • Create the request
    • Set simple properties
    • Call BeginGetRequestStream
  • In the callback handler for BeginGetRequestStream
    • Write out the body data
    • Call BeginGetResponse
  • In the callback handler for BeginGetResponse
    • Handle the response data

Alternatively, unless you have to use the asynchronous calls, you could just create a separate thread and use the synchronous versions instead. Until the language support in C# 5, that would be simpler.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文