C# 请求未超时

发布于 2024-10-08 13:17:27 字数 5062 浏览 3 评论 0原文

我有这段代码在BackgroundWorker 中运行,并且应该向服务器发出POST 请求并获得响应。当它应该工作时它工作得很好,但是当我尝试引发 404 错误时,它不会捕获错误报告系统。

loginProcess.DoWork += delegate(object s, DoWorkEventArgs args)
            {
                // loginProcess BackgroundWorker

                try 
                {
                    // Try to login, if error, report

                    loginProcess.ReportProgress(10);
                    String method = "POST";
                    String postdata = "postdata=test";
                    String url = "http://localhost/dev/login.php";

                    loginProcess.ReportProgress(15);




                    WebRequest rqst = HttpWebRequest.Create(url);
                    rqst.Timeout = 5000;
                    ((HttpWebRequest)rqst).KeepAlive = true;

                    loginProcess.ReportProgress(20);


                    //rqst.Timeout = this.Timeout;
                    // only needed, if you use HTTP AUTH
                    //CredentialCache creds = new CredentialCache();
                    //creds.Add(new Uri(url), "Basic", new NetworkCredential(this.Uname, this.Pwd));
                    //rqst.Credentials = creds;
                    rqst.Method = method;
                    if (!String.IsNullOrEmpty(postdata))
                    {
                        //rqst.ContentType = "application/xml";
                        rqst.ContentType = "application/x-www-form-urlencoded";
                        loginProcess.ReportProgress(30);

                        byte[] byteData = UTF8Encoding.UTF8.GetBytes(postdata);

                        loginProcess.ReportProgress(40);

                        rqst.ContentLength = byteData.Length;

                        loginProcess.ReportProgress(50);
                        using (Stream postStream = rqst.GetRequestStream())
                        {


                            loginProcess.ReportProgress(50);
                            postStream.Write(byteData, 0, byteData.Length);
                            loginProcess.ReportProgress(60);
                            postStream.Close();
                            loginProcess.ReportProgress(70);    
                            rqst.GetResponse().Close();
                            rqst.GetRequestStream().Close();
                        }




                    }

                    loginProcess.ReportProgress(90);
                    using (var response1 = rqst.GetResponse())
                    {
                        using (var responseStream1 = response1.GetResponseStream())
                        {
                            using (var reader1 = new StreamReader(responseStream1))
                            {
                            //StreamReader rsps = new StreamReader(rqst.GetResponse().GetResponseStream());

                            string strRsps = reader1.ReadToEnd();
                            loginProcess.ReportProgress(95);
                            loginVars = strRsps;

                            //rqst.
                            //reader1.Close();
                            //rsps.Dispose();
                            }

                            args.Result = "SUCCESS";
                        }
                    }







                }
                catch(WebException err)
                {
                    // Catch error and put into err variable

                    if(err.Status == WebExceptionStatus.ProtocolError) 
                    {
                        // If something is wrong with protocol
                        LoginReporting.ErrorName = Convert.ToString(((HttpWebResponse)err.Response).StatusCode);
                        LoginReporting.ErrorDescription = Convert.ToString(((HttpWebResponse)err.Response).StatusDescription);
                        LoginReporting.ErrorNotes = "Error when logging in, Server returned: " + Convert.ToString(((HttpWebResponse)err.Response).StatusCode);
                        LoginReporting.ErrorLocation = "LoginRequest.ProtocolError";

                        args.Result = "ERROR";
                        //MessageBox.Show(Convert.ToString(((HttpWebResponse)err.Response).StatusCode));
                    //MessageBox.Show(Convert.ToString(((HttpWebResponse)err.Response).StatusDescription));
                    }
                    else
                    {
                    args.Result = "ERROR";
                    }

                }
                catch(Exception err) 
                {
                    // Catch unhandled error

                    LoginReporting.ErrorName = Convert.ToString(err);
                        LoginReporting.ErrorDescription = Convert.ToString(err.Message);
                        LoginReporting.ErrorNotes = "Error when logging in, Server returned: " + Convert.ToString(err.Message);
                        LoginReporting.ErrorLocation = "LoginRequest.ProtocolError";

                    args.Result = "ERROR";

                }
            };

我已经对请求设置了超时,但它不起作用!这是一个错误,还是我在这里做错了什么?

谢谢

I have this code which runs in a BackgroundWorker, and should make a POST request to the server and get a response. It works fine when it is supposed to work, but when I try to induce a 404 error it doesn't catch the error reporting system.

loginProcess.DoWork += delegate(object s, DoWorkEventArgs args)
            {
                // loginProcess BackgroundWorker

                try 
                {
                    // Try to login, if error, report

                    loginProcess.ReportProgress(10);
                    String method = "POST";
                    String postdata = "postdata=test";
                    String url = "http://localhost/dev/login.php";

                    loginProcess.ReportProgress(15);




                    WebRequest rqst = HttpWebRequest.Create(url);
                    rqst.Timeout = 5000;
                    ((HttpWebRequest)rqst).KeepAlive = true;

                    loginProcess.ReportProgress(20);


                    //rqst.Timeout = this.Timeout;
                    // only needed, if you use HTTP AUTH
                    //CredentialCache creds = new CredentialCache();
                    //creds.Add(new Uri(url), "Basic", new NetworkCredential(this.Uname, this.Pwd));
                    //rqst.Credentials = creds;
                    rqst.Method = method;
                    if (!String.IsNullOrEmpty(postdata))
                    {
                        //rqst.ContentType = "application/xml";
                        rqst.ContentType = "application/x-www-form-urlencoded";
                        loginProcess.ReportProgress(30);

                        byte[] byteData = UTF8Encoding.UTF8.GetBytes(postdata);

                        loginProcess.ReportProgress(40);

                        rqst.ContentLength = byteData.Length;

                        loginProcess.ReportProgress(50);
                        using (Stream postStream = rqst.GetRequestStream())
                        {


                            loginProcess.ReportProgress(50);
                            postStream.Write(byteData, 0, byteData.Length);
                            loginProcess.ReportProgress(60);
                            postStream.Close();
                            loginProcess.ReportProgress(70);    
                            rqst.GetResponse().Close();
                            rqst.GetRequestStream().Close();
                        }




                    }

                    loginProcess.ReportProgress(90);
                    using (var response1 = rqst.GetResponse())
                    {
                        using (var responseStream1 = response1.GetResponseStream())
                        {
                            using (var reader1 = new StreamReader(responseStream1))
                            {
                            //StreamReader rsps = new StreamReader(rqst.GetResponse().GetResponseStream());

                            string strRsps = reader1.ReadToEnd();
                            loginProcess.ReportProgress(95);
                            loginVars = strRsps;

                            //rqst.
                            //reader1.Close();
                            //rsps.Dispose();
                            }

                            args.Result = "SUCCESS";
                        }
                    }







                }
                catch(WebException err)
                {
                    // Catch error and put into err variable

                    if(err.Status == WebExceptionStatus.ProtocolError) 
                    {
                        // If something is wrong with protocol
                        LoginReporting.ErrorName = Convert.ToString(((HttpWebResponse)err.Response).StatusCode);
                        LoginReporting.ErrorDescription = Convert.ToString(((HttpWebResponse)err.Response).StatusDescription);
                        LoginReporting.ErrorNotes = "Error when logging in, Server returned: " + Convert.ToString(((HttpWebResponse)err.Response).StatusCode);
                        LoginReporting.ErrorLocation = "LoginRequest.ProtocolError";

                        args.Result = "ERROR";
                        //MessageBox.Show(Convert.ToString(((HttpWebResponse)err.Response).StatusCode));
                    //MessageBox.Show(Convert.ToString(((HttpWebResponse)err.Response).StatusDescription));
                    }
                    else
                    {
                    args.Result = "ERROR";
                    }

                }
                catch(Exception err) 
                {
                    // Catch unhandled error

                    LoginReporting.ErrorName = Convert.ToString(err);
                        LoginReporting.ErrorDescription = Convert.ToString(err.Message);
                        LoginReporting.ErrorNotes = "Error when logging in, Server returned: " + Convert.ToString(err.Message);
                        LoginReporting.ErrorLocation = "LoginRequest.ProtocolError";

                    args.Result = "ERROR";

                }
            };

I have put a timeout on the request but it just doesn't work! Is this a bug, or am I doing something wrong here?

Thanks

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

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

发布评论

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

评论(2

怀念你的温柔 2024-10-15 13:17:27

404 仍然是服务器对客户端请求的响应。您是否尝试停止服务器并查看代码是否捕获异常。

A 404 is still a response from the server to the client's request. Did you try stopping the server and see if you code catches the exception.

茶色山野 2024-10-15 13:17:27

您在 rqst.GetResponse().Close(); 中关闭了 Response,然后尝试使用 rqst.GetResponse() 访问 Stream。
只需注释掉rqst.GetResponse().Close(); 它应该可以工作......

You closed the Response in rqst.GetResponse().Close(); and then you try to access the Stream with rqst.GetResponse().
Just comment out rqst.GetResponse().Close(); and it should work...

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