从Web服务对服务器执行POST

时间:2013-07-31 09:36:19

标签: c# .net web-services browser

托管了一些向ASPX页面执行POST的Web服务。

代码:

 [WebMethod]
        public string Test()
        {
            sb.AppendLine("Start");
            try
            {
                var t = new Thread(MyThreadStartMethod);
                t.SetApartmentState(ApartmentState.STA);
                t.Start();
                t.Join();
            }
            catch (Exception ex)
            {
                sb = sb.AppendLine(ex.ToString());
            }
            sb.AppendLine("Finish");
            return sb.ToString();
        }

         private void MyThreadStartMethod(object obj)
        {
            try
            {
                WebBrowser browser = new WebBrowser();
                browser.DocumentCompleted += browser_DocumentCompleted;
                browser.Url = new Uri("http://www.wikipedia.com");
                while (browser.ReadyState != WebBrowserReadyState.Complete)
                {
                    System.Windows.Forms.Application.DoEvents();
                    Thread.Sleep(60);
                }
            }
            catch (Exception ex)
            {
                sb = sb.AppendLine(ex.ToString());
            }
        }

        void browser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            sb = sb.AppendLine("Document completed: " + e.Url);
        }

尝试在我的共享托管服务器上运行时,我总是会收到超时错误。

尝试下一个代码来检查我是否可以连接到第三方地址并且它正常工作。

private bool checkUrl(string url)
{
    try
    {
        HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
        request.Method = "HEAD";
        HttpWebResponse response = request.GetResponse() as HttpWebResponse;
        return (response.StatusCode == HttpStatusCode.OK);
    }
    catch
    {
        return false;
    }
}

任何人都可以解释运行第一个代码的问题?他们阻止了什么吗?

1 个答案:

答案 0 :(得分:0)

您必须从代码中删除后两行

System.Windows.Forms.Application.DoEvents();
Thread.Sleep(60);

因为它阻止了您的webbrowser控件完成Navigate。

Hans Passant提出了关于如何在单独的线程中运行WebBrowser控件的best sample