简体   繁体   English

C#请求未超时

[英]C# Request not timing out

I have this code which runs in a BackgroundWorker, and should make a POST request to the server and get a response. 我有运行在BackgroundWorker中的这段代码,应该向服务器发出POST请求并获得响应。 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. 它应该可以正常工作,但是当我尝试引发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 put a timeout on the request but it just doesn't work! 我在请求上设置了超时时间,但是那根本不起作用! Is this a bug, or am I doing something wrong here? 这是一个错误,还是我在这里做错了什么?

Thanks 谢谢

A 404 is still a response from the server to the client's request. 404仍然是服务器对客户端请求的响应。 Did you try stopping the server and see if you code catches the exception. 您是否尝试停止服务器并查看代码是否捕获了异常。

You closed the Response in rqst.GetResponse().Close(); 您在rqst.GetResponse().Close();关闭了响应rqst.GetResponse().Close(); and then you try to access the Stream with rqst.GetResponse() . 然后尝试使用rqst.GetResponse()访问Stream。
Just comment out rqst.GetResponse().Close(); 只需注释掉rqst.GetResponse().Close(); and it should work... 它应该工作...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM