Unanswered Return CookiesContainer object from WCF service to client

  • Sunday, September 09, 2012 8:03 AM
     
      Has Code

    I want to return CookiesContainer object from WCF service but I cann't return. I can return string from service.

    Here is my Web.config

    <?xml version="1.0" encoding="UTF-8"?>
    <configuration>
      <system.web>
        <compilation debug="true" targetFramework="4.0" />
            <authentication mode="Windows">
                <forms cookieless="UseCookies" requireSSL="false" />
            </authentication>
      </system.web>
      
      <system.serviceModel>
           
        <services>
          <service name="WcfService1.Service1" behaviorConfiguration="ServiceBehaviour">
            <endpoint address="" binding="basicHttpBinding" bindingConfiguration="" contract="WcfService1.IService1" />
            <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
          </service>
        </services>
           
        <behaviors>
          <serviceBehaviors>
            <behavior name="ServiceBehaviour">
             <!--<behavior>-->
              <serviceMetadata httpGetEnabled="true" />
              <serviceDebug includeExceptionDetailInFaults="true" />
            </behavior>
          </serviceBehaviors>
        </behaviors>
        <client>
          <endpoint address="http://localhost/WcfService1/Service1.svc"
            binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IService1"
            contract="ServiceReference1.IService1" name="BasicHttpBinding_IService1" />
        </client>
        
        <bindings>
          <basicHttpBinding>
            <binding name="BasicHttpBinding_IService1" closeTimeout="00:01:00"
              openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
              allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
              maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
              messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
              useDefaultWebProxy="true">
              <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
                maxBytesPerRead="4096" maxNameTableCharCount="16384" />
              <security mode="None">
                <transport clientCredentialType="None" proxyCredentialType="None"
                  realm="" />
                <message clientCredentialType="UserName" algorithmSuite="Default" />
              </security>
            </binding>
          </basicHttpBinding>
        </bindings>
        
            <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
      </system.serviceModel>
      
     <system.webServer>
        <modules runAllManagedModulesForAllRequests="true" />
      </system.webServer>
      
    </configuration>

    Here is myIService1.cs

    using System; 
    using System.Collections.Generic; 
    using System.Linq; 
    using System.Runtime.Serialization; 
    using System.ServiceModel; 
    using System.ServiceModel.Web; 
    using System.Text; 
    using System.Net; 
    using System.IO; 
    using System.Web; 
     
    namespace WcfService1 
    { 
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together. 
    [ServiceContract] 
    public interface IService1 
    { 
        [OperationContract] 
        CookieCollection GetCookies(); 
     
        [OperationContract] 
        CookieContainer GetConnect(string uname, string password); 
        //string GetConnect(string uname, string password); 
    } 
    } 

    Here is my Service1.svc.cs

    using System; 
    using System.Collections.Generic; 
    using System.Linq; 
    using System.Runtime.Serialization; 
    using System.ServiceModel; 
    using System.ServiceModel.Web; 
    using System.Text; 
    using System.Net; 
    using System.IO; 
    using System.Web; 
     
    namespace WcfService1 
    { 
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together. 
    public class Service1 : IService1 
    { 
        public CookieCollection GetCookies() 
        { 
            HttpWebRequest req; 
            CookieCollection cc = new CookieCollection(); 
            req = null; 
     
            req = (HttpWebRequest)WebRequest.Create("http://site5.way2sms.com/"); 
            req.CookieContainer = new CookieContainer(); 
            // req.CookieContainer.Add(cc); 
     
            req.CookieContainer.Add(cc); 
            req.KeepAlive = true; 
     
            req.UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11"; 
            req.ContentType = "application/x-www-form-urlencoded"; 
            req.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"; 
     
            req.Referer = "http://site5.way2sms.com/content/index.html"; 
     
            req.AllowAutoRedirect = true; 
            req.ServicePoint.Expect100Continue = true; 
     
            return ((HttpWebResponse)req.GetResponse()).Cookies; 
        } 
     
        public CookieContainer GetConnect(string uid, string password) 
        //public string GetConnect(string uid, string password) 
        { 
            HttpWebRequest req; 
            HttpWebResponse res; 
            Stream str; 
     
     
            //try 
            //{ 
                req = (HttpWebRequest)WebRequest.Create("http://site5.way2sms.com/Login1.action"); 
                req.Method = "POST"; 
                CookieContainer con = new CookieContainer(); 
                req.CookieContainer = con; 
                req.CookieContainer.Add(GetCookies()); 
                req.KeepAlive = true; 
     
                req.UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11"; 
                req.ContentType = "application/x-www-form-urlencoded"; 
                req.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"; 
     
                req.Referer = "http://site5.way2sms.com/content/index.html"; 
     
                byte[] data = System.Text.Encoding.Default.GetBytes("username=" + uid + "&password=" + password); 
                req.Credentials = new NetworkCredential(uid, password); 
                req.ContentLength = data.Length; 
                req.AllowAutoRedirect = true; 
                req.ServicePoint.Expect100Continue = true; 
     
                str = req.GetRequestStream(); 
                str.Write(data, 0, data.Length); 
                str.Close(); 
     
     
                res = (HttpWebResponse)req.GetResponse(); 
     
                string iduri = System.Web.HttpUtility.ParseQueryString(res.ResponseUri.Query).Get("id"); 
     
                if (iduri != "") 
                { 
                    return con; 
                    //return "Success"; 
                } 
                else 
                { 
                    res.Close(); 
                    str.Close(); 
     
                    return null; 
                    //return "Fail"; 
                } 
            //} 
            //catch (Exception ex) 
            //{ 
     
            //} 
        } 
      } 
     } 

    Here is my Login.xaml.cs

      private void btnSignin_Click(object sender, RoutedEventArgs e) 
        { 
            string uid = txtUsername.Text.Trim(); 
            string password = txtPassword.Password.Trim(); 
     
            networkIsAvailable = Checknetwork(); 
            if (networkIsAvailable) 
            { 
                MessageBox.Show("Network Avaliable", "Avaliable", MessageBoxButton.OK); 
                //svc.GetcookiesCompleted += new EventHandler<GetcookiesCompletedEventArgs>(svc_Get_Cookies); 
                //svc.GetcookiesAsync();  
     
                txtblockcheck.Visibility = Visibility.Visible; 
                svc.GetConnectCompleted += new EventHandler<GetConnectCompletedEventArgs>(svc_Get_Connected); 
                svc.GetConnectAsync(uid, password); 
            } 
            else 
            { 
                MessageBox.Show("Please check your network", "Warning", MessageBoxButton.OK); 
            } 
        } 
     
     
        void svc_Get_Connected(object send, GetConnectCompletedEventArgs e) 
        { 
            CookieContainer con = e.Result; 
        } 

    When I return CookiesContainer from service I get this following error

    There was no endpoint listening at http://localhost:3922/Service1.svc that could accept the message. This is often caused by an incorrect address or SOAP action. See InnerException, if present, for more details.

    I doesn't understand how can I return CookiesContainer Object from service to client.



    • Edited by Ajay Punekar Tuesday, September 11, 2012 9:39 AM
    •  

All Replies

  • Tuesday, September 11, 2012 7:22 AM
    Moderator
     
      Has Code

    Hi,

    In Web.config, you only set the client node, but the service will load the service node for setting the endpoint:

    Please delete the client node and add the code as below:

        <services>
          <service name="MyServiceReference.Service1">
          <endpoint address="http://localhost:3922/Service1.svc" binding="basicHttpBinding"
           bindingConfiguration="BasicHttpBinding_IService1" contract="MyServiceReference.IService1"
           name="BasicHttpBinding_IService1" />
          </service>
        </services>

  • Tuesday, September 11, 2012 9:41 AM
     
     

    I have change my web.config file.

    Can you please check it.

  • Wednesday, September 12, 2012 2:31 AM
    Moderator
     
     

    Sure,

    Please provide the web.config.

    Also , if you can share your project with me would be more appreciated.

  • Wednesday, September 12, 2012 4:54 PM
     
      Has Code
    <?xml version="1.0"?>
    <configuration>
      <system.web>
        <compilation debug="true" targetFramework="4.0" />
        <authentication mode="Windows">
          <forms cookieless="UseCookies" requireSSL="false" />
        </authentication>
      </system.web>
      <system.serviceModel>
        
        <bindings>
          <basicHttpBinding>
            <binding name="BasicHttpBinding_IService1" closeTimeout="00:10:00"
              openTimeout="00:10:00" receiveTimeout="00:10:00" sendTimeout="00:10:00"
              allowCookies="true" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
              maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
              messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
              useDefaultWebProxy="true">
              <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
                maxBytesPerRead="4096" maxNameTableCharCount="16384" />
              <security mode="None">
                <transport clientCredentialType="None" proxyCredentialType="None"
                  realm="" />
                <message clientCredentialType="UserName" algorithmSuite="Default" />
              </security>
            </binding>
          </basicHttpBinding>
        </bindings>
        <client>
          <endpoint address="http://localhost/WebService/Service1.svc"
            binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IService1"
            contract="ServiceReference1.IService1" name="BasicHttpBinding_IService1" />
        </client>
        <services>
          <service name="WcfService1.Service1" behaviorConfiguration="ServiceBehaviour">
            <endpoint address="" binding="basicHttpBinding" bindingConfiguration="" contract="WcfService1.IService1" />
            <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
          </service>
        </services>
        
        <behaviors>
          <serviceBehaviors>
            <behavior name="ServiceBehaviour">
              <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
              <serviceMetadata httpGetEnabled="true"/>
              <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
              <serviceDebug includeExceptionDetailInFaults="false"/>
            </behavior>
          </serviceBehaviors>
        </behaviors>
        <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
      </system.serviceModel>
     <system.webServer>
        <modules runAllManagedModulesForAllRequests="true"/>
      </system.webServer>
      
    </configuration>

    Here is my web.config
  • Thursday, September 13, 2012 1:59 AM
    Moderator
     
      Has Code

    Hi,

    After a little change to your web.config , it is as below add the dictionaryBrowse and delete the client node(client node is for client side ,not service side):

    <?xml version="1.0"?>
    <configuration>
      <system.web>
        <compilation debug="true" targetFramework="4.5" />
        <authentication mode="Windows">
          <forms cookieless="UseCookies" requireSSL="false" />
        </authentication>
      </system.web>
      <system.serviceModel>
        <bindings>
          <basicHttpBinding>
            <binding name="BasicHttpBinding_IService1" closeTimeout="00:10:00"
              openTimeout="00:10:00" receiveTimeout="00:10:00" sendTimeout="00:10:00"
              allowCookies="true" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
              maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
              messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
              useDefaultWebProxy="true">
              <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
                maxBytesPerRead="4096" maxNameTableCharCount="16384" />
              <security mode="None">
                <transport clientCredentialType="None" proxyCredentialType="None"
                  realm="" />
                <message clientCredentialType="UserName" algorithmSuite="Default" />
              </security>
            </binding>
          </basicHttpBinding>
        </bindings>
        <services>
          <service behaviorConfiguration="ServiceBehaviour" name="WcfService1.Service1">
            <endpoint address="" binding="basicHttpBinding" bindingConfiguration=""
              contract="WcfService1.IService1" />
            <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
          </service>
        </services>
        <behaviors>
          <serviceBehaviors>
            <behavior name="ServiceBehaviour">
              <serviceMetadata httpGetEnabled="true"/>
              <serviceDebug includeExceptionDetailInFaults="false"/>
            </behavior>
          </serviceBehaviors>
        </behaviors>
        <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
      </system.serviceModel>
      <system.webServer>
        <modules runAllManagedModulesForAllRequests="true"/>
        <directoryBrowse enabled="true"/>
      </system.webServer>
    </configuration>

    More ,test Code:

    [ServiceContract]
        public interface IService1
        {
            [OperationContract]
            CookieContainer GetConnect(string username, string password);
        }
        [DataContract]
        public class CookieContainer
        {
            bool boolValue = true;
            string stringValue = "Hello ";
            [DataMember]
            public bool BoolValue
            {
                get { return boolValue; }
                set { boolValue = value; }
            }
            [DataMember]
            public string StringValue
            {
                get { return stringValue; }
                set { stringValue = value; }
            }
        }


        public class Service1 : IService1
        {
            public CookieContainer GetConnect(string username, string password)
            {
                return new CookieContainer() { BoolValue = true, StringValue = username + password };
            }
        }

    Then click the Service1.svc file in solution , then press F5 , you can open WCF test Client.exe.

    Test as below:

  • Saturday, September 15, 2012 8:06 AM
     
      Has Code

    I share my code Iservice1.cs,Service1.svc.cs, client side code

    IService1.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Runtime.Serialization;
    using System.ServiceModel;
    using System.ServiceModel.Web;
    using System.Text;
    using System.Net;
    using System.IO;
    using System.Runtime.Serialization.Formatters.Binary;
    namespace WcfService1
    {
        // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
        [ServiceContract]
        public interface IService1
        {
    
            // TODO: Add your service operations here
    
            [OperationContract]
            CookieContainer GetConnect(string uid, string password);
    
        }
    
        // Use a data contract as illustrated in the sample below to add composite types to service operations.
        
    }
    

    Service1.svc.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Runtime.Serialization;
    using System.ServiceModel;
    using System.ServiceModel.Web;
    using System.Text;
    using System.Net;
    using System.IO;
    using System.Data;
    using System.Runtime.Serialization.Formatters.Binary;
    using System.Xml.Serialization;
    using System.Xml;
    using Newtonsoft.Json.Serialization;
    
    
    namespace WcfService1
    {
        // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
        public class Service1 : IService1
        {
          public CookieContainer con;
          public CookieCollection GetCookies()
            {
                HttpWebRequest req;
                CookieCollection cc = new CookieCollection();
                req = null;
    
                req = (HttpWebRequest)WebRequest.Create("http://site5.way2sms.com/");
                req.CookieContainer = new CookieContainer();
                // req.CookieContainer.Add(cc);
    
                req.CookieContainer.Add(cc);
                req.KeepAlive = true;
    
                req.UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11";
                req.ContentType = "application/x-www-form-urlencoded";
                req.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
    
                req.Referer = "http://site5.way2sms.com/content/index.html";
    
                req.AllowAutoRedirect = true;
                req.ServicePoint.Expect100Continue = true;
    
                return ((HttpWebResponse)req.GetResponse()).Cookies;
            }
    
            //public string GetConnect(string uid, string password)
            public CookieContainer GetConnect(string uid, string password)
            {
                HttpWebRequest req;
                HttpWebResponse res;
                Stream str;
                
    
                try
                {
                    req = (HttpWebRequest)WebRequest.Create("http://site5.way2sms.com/Login1.action");
                    req.Method = "POST";
                    con = new CookieContainer();
                    req.CookieContainer = con;
                    req.CookieContainer.Add(GetCookies());
                    req.KeepAlive = true;
    
                    req.UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11";
                    req.ContentType = "application/x-www-form-urlencoded";
                    req.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
    
                    req.Referer = "http://site5.way2sms.com/content/index.html";
    
                    byte[] data = System.Text.Encoding.Default.GetBytes("username=" + uid + "&password=" + password);
                    req.Credentials = new NetworkCredential(uid, password);
                    req.ContentLength = data.Length;
                    req.AllowAutoRedirect = true;
                    req.ServicePoint.Expect100Continue = true;
    
                    str = req.GetRequestStream();
                    str.Write(data, 0, data.Length);
                    str.Close();
                    str.Flush();
    
                    res = (HttpWebResponse)req.GetResponse();
    
                    string iduri = System.Web.HttpUtility.ParseQueryString(res.ResponseUri.Query).Get("id");
    
                    if (iduri != "")
                    {
                        // return "Success";
                        return con;
                    }
                    else
                    {
                        res.Close();
                        return null;
                       // return "Fail";
                    }
                }
                catch (Exception ex)
                {
                    return null;
                }
            }

    ClientSide code i.e. Windows phone 7

     svc.GetConnectCompleted += new EventHandler<GetConnectCompletedEventArgs>(svc_Get_Connected);
    svc.GetConnectAsync(uid, password);
    
    
    
     void svc_Get_Connected(object send, GetConnectCompletedEventArgs e)
    {
         CookieContainer con = e.Result;
    }

    My service didn't return Cookiecontainer object i.e. con