C# 将CookiesContainer对象从WCF服务返回到客户端

C# 将CookiesContainer对象从WCF服务返回到客户端,c#,wcf,windows-phone-7.1,C#,Wcf,Windows Phone 7.1,我想从WCF服务返回CookiesContainer对象,但无法返回。我可以从服务中返回字符串 这是我的Web.config <?xml version="1.0" encoding="UTF-8"?> <configuration> <system.web> <compilation debug="true" targetFramework="4.0" /> <authentication mode="Windows">

我想从WCF服务返回CookiesContainer对象,但无法返回。我可以从服务中返回字符串

这是我的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="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>

    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>

<system.webServer>
   <modules runAllManagedModulesForAllRequests="true" />
</system.webServer>

</configuration>
这是我的服务1.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 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);
}
}
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)
        //{

        //}
    }
  }
 }
    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;
    }
这是我的Login.xaml.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);
}
}
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)
        //{

        //}
    }
  }
 }
    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;
    }
private void btnSignin\u单击(对象发送方,路由目标方)
{
string uid=txtUsername.Text.Trim();
字符串password=txtPassword.password.Trim();
networkIsAvailable=Checknetwork();
如果(网络可用)
{
显示(“网络可用”,“可用”,MessageBox按钮。确定);
//svc.GetcookiesCompleted+=新事件处理程序(svc\u Get\u Cookies);
//GetcookiesAsync();
txtblockcheck.Visibility=可见性.Visibility;
svc.GetConnectCompleted+=新事件处理程序(svc\u Get\u Connected);
GetConnectAsync(uid,密码);
}
其他的
{
显示(“请检查您的网络”,“警告”,MessageBox按钮。确定);
}
}
void svc_Get_Connected(对象发送,GetConnectCompletedEventArgs e)
{
CookieContainer con=e.结果;
}
当我从服务返回CookiesContainer时,我得到以下错误

http://localhost:3922/Service1.svc可以接受该消息。这通常是由不正确的地址或SOAP操作引起的。有关更多详细信息,请参阅InnerException(如果存在)

我不明白如何将CookiesContainer对象从服务返回到客户端
有人能告诉我吗?

如果没有其他帮助,为了帮助调试,我会手动运行序列化。CookieContainer不是XmlSerializable(而是Soap可序列化的,所以这不应该是真正的问题),但是除了通过webservices编写的POCO对象之外,我从来不喜欢发送任何东西

这是我的通用序列化方法,可能只是向它提供字节数组,或者
Convert.ToBase64String()
并返回它。如果没有其他事情,这将绝对确认您的Web服务正在按预期工作

使用以下方法:

public byte[] GetConnect(string uid, string password)
{
    ...

    if (iduri != "")
    {
        return SerializeObject(con);
    }
}
-

void svc\u Get\u Connected(对象发送,GetConnectCompletedEventArgs e)
{
CookieContainer con=反序列化对象(如结果);
}
-

公共静态字节[]序列化对象(T obj)
{
尝试
{
使用(MemoryStream MemoryStream=new MemoryStream())
{
BinaryFormatter xs=新的BinaryFormatter();
序列化(memoryStream,obj);
返回memoryStream.ToArray();
}
}
抓住
{
返回null;
}
}
公共静态T反序列化对象(字节[]xml)
{
BinaryFormatter xs=新的BinaryFormatter();
MemoryStream MemoryStream=新的MemoryStream(xml);
返回(T)xs.反序列化(memoryStream);
}
我们试试这个:

  • 在客户端项目中,转到服务参考,右键单击,然后点击更新服务参考。每次更改服务标志(任何方法或参数)时,都必须更新此引用。也许你做了一些改变,忘记了这一步

  • 以防万一,在接口和服务定义中设置params names equals。注意
    CookieContainer GetConnect(字符串uname,字符串密码)指定
    字符串uname
    ,但Service1实现声明
    CookieContainer GetConnect(字符串uid,字符串密码),使用
    字符串uid
    。这不应该是个问题,只是为了整洁


  • 错误消息似乎与您建议的问题无关。当我返回CookieContainer对象时,它给出了一个我上面提到的错误,我可以轻松地从服务返回字符串。但是我不能返回CookiesContainer,我得到了同样的错误。服务无法返回cookiecontainer对象。隔离它,我刚刚尝试设置一个全新的解决方案,包括两个项目,WCF和一个控制台客户端,使用与您相同的代码,它正在工作。因此,使用默认配置的代码没有问题。如何隔离它?你能把你的密码寄出去吗?您的web.config、service1.svc、Iservice1.csi在我的第一条评论中,我告诉您我使用了相同的代码,因此没有必要发布它。我还说,我使用此代码和客户端和服务的默认配置创建了解决方案,它工作了,然后您应该尝试执行相同的操作,这样您就会发现问题所在。我在具有相同设置的新解决方案中尝试了所有这一切,但问题没有再次得到解决。在新解决方案中会出现相同的错误。它给出了相同的错误i.eThere没有端点列表我不知道如何使用它?如何在.xaml.cs文件中使用BinaryFormatter?我给出错误,即缺少assemblyMy服务成功返回SerializeObject(con)。现在我不知道如何从svc_Get_Connected函数调用反序列化对象函数我不能在Windows phone中使用BinaryFormatter,所以有没有办法编写反序列化对象方法?