none
调用WCF中异步请求的问题 RRS feed

  • 问题

  • 各位大侠,小弟最近想做个Sl站点,但是困难重重啊,以前是做Abap的,在学校里学的一些.NET也都忘的差不多了,感觉要学的东西好多。言归正传,我把异步请求都写在了SL的WCF中,想调用getPage方法来完成这个请求并取得获得的page页面,然后通过getStr方法来返回,但是WCF中的执行顺序会变的很奇怪,有时getPage执行了一半突然就调用getStr了,所以一直取不到值,Sl里只能用异步,请问代码怎么改动能解决这个问题?谢谢!
    -------------------------------------------------------
    CustomerService.svc.cs
        public class CustomerService
        {
            private string sect;
            private string page;
           
            [OperationContract]
            public void getPage(string uri, string sect)
            {
                this.sect = sect;
                Uri endpoint = new Uri(uri);
                WebRequest request = WebRequest.Create(endpoint);
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                request.BeginGetRequestStream(new AsyncCallback(RequestReady), request);
            }

            private void RequestReady(IAsyncResult asyncResult)
            {
                WebRequest request = asyncResult.AsyncState as WebRequest;
                Stream requestStream = request.EndGetRequestStream(asyncResult);
                using (StreamWriter writer = new StreamWriter(requestStream))
                {
                    writer.Write(this.sect);
                    writer.Flush();
                }
                request.BeginGetResponse(new AsyncCallback(ResponseReady), request);
            }

            private void ResponseReady(IAsyncResult asyncResult)
            {
                WebRequest request = asyncResult.AsyncState as WebRequest;
                WebResponse response = request.EndGetResponse(asyncResult);
                using (Stream responseStream = response.GetResponseStream())
                {
                    StreamReader reader = new StreamReader(responseStream);
                    this.page = reader.ReadToEnd();
                }
            }

            [OperationContract]
            public string getStr()
            {
                return this.page;
            }
        }
    -------------------------------------------------------
    Page.xaml.cs
        private void btnLogMail_Click(object sender, RoutedEventArgs e)
        {
            CustomerServiceClient client = new CustomerServiceClient();
            client.getPageCompleted += new EventHandler<AsyncCompletedEventArgs>(client_getPageCompleted);
            client.getPageAsync("http://mail.sina.com.cn/cgi-bin/login.cgi", "u=您的新浪用户名&psw=您的新浪密码"); //:-P
            client.getStrCompleted += new EventHandler<getStrCompletedEventArgs>(client_getStrCompleted);
            client.getStrAsync();
        }
        void client_getPageCompleted(object sender, AsyncCompletedEventArgs e) { }
        void client_getStrCompleted(object sender, getStrCompletedEventArgs e)
        {
            string page = e.Result; // ResponseReady(...)还没走就已经返回null了,郁闷...
        }
    -------------------------------------------------------

    2009年5月13日 7:35

答案

  • 建个轻量级的ashx就能取回页面流

    using System;
    using System.Collections;
    using System.Data;
    using System.Linq;
    using System.Web;
    using System.Web.Services;
    using System.Web.Services.Protocols;
    using System.Xml.Linq;
    using System.Net;
    
    namespace ReadGifBySL3.Web
    {
        /// <summary>
        /// Summary description for $codebehindclassname$
        /// </summary>
        [WebService(Namespace = "http://tempuri.org/")]
        [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
        public class ClientAccess : IHttpHandler
        {
    
            public void ProcessRequest(HttpContext context)
            {
                WebClient client = new WebClient();
                byte[] bytes = client.DownloadData(new Uri(context.Request["url"].ToString()));
                context.Response.BinaryWrite(bytes);
            }
    
            public bool IsReusable
            {
                get
                {
                    return false;
                }
            }
        }
    }
    

    你可以参考下http://gifimage.codeplex.com/ 这个控件,里面有一个我写的ClientAccess.ashx为了通过跨域访问所用的web代理

    而且楼主的程序好像不对哦,WCF里两个公开方法不能这么混搭着用,补一下wcf基础吧:)
    2009年5月13日 15:18
    版主

全部回复

  • 建个轻量级的ashx就能取回页面流

    using System;
    using System.Collections;
    using System.Data;
    using System.Linq;
    using System.Web;
    using System.Web.Services;
    using System.Web.Services.Protocols;
    using System.Xml.Linq;
    using System.Net;
    
    namespace ReadGifBySL3.Web
    {
        /// <summary>
        /// Summary description for $codebehindclassname$
        /// </summary>
        [WebService(Namespace = "http://tempuri.org/")]
        [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
        public class ClientAccess : IHttpHandler
        {
    
            public void ProcessRequest(HttpContext context)
            {
                WebClient client = new WebClient();
                byte[] bytes = client.DownloadData(new Uri(context.Request["url"].ToString()));
                context.Response.BinaryWrite(bytes);
            }
    
            public bool IsReusable
            {
                get
                {
                    return false;
                }
            }
        }
    }
    

    你可以参考下http://gifimage.codeplex.com/ 这个控件,里面有一个我写的ClientAccess.ashx为了通过跨域访问所用的web代理

    而且楼主的程序好像不对哦,WCF里两个公开方法不能这么混搭着用,补一下wcf基础吧:)
    2009年5月13日 15:18
    版主
  • 谢谢版主的回答,那我想请教一下如果用原来的方法该怎么样来实现啊?不用ashx来做。我试了很久还是感觉有些问题。

    2009年5月15日 14:26
  •         /// <summary>
            /// 取得网址内容
            /// </summary>
            /// <param name="requestUri">网址</param>
            /// <param name="strCharset">编码</param>
            /// <returns></returns>
            public string GetUrlContent(string requestUri, string strCharset)
            {
                string strcontent = "";
                try
                {
                    WebRequest wrquest = WebRequest.Create(requestUri);
                    WebResponse wrponse = wrquest.GetResponse();
                    StreamReader sr = new StreamReader(wrponse.GetResponseStream(), System.Text.Encoding.GetEncoding(strCharset));
                    strcontent = sr.ReadToEnd();               
                }
                catch
                { }
                return strcontent;
            }

    wcf中用这个方法一个函数就取得内容返回了
    2009年5月15日 14:58
    版主