3

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>

これが私の 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.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);
}
}

これが私の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)
        //{

        //}
    }
  }
 }

これが私の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;
    }

サービスからCookiesContainerを返すと、次のエラーが発生します

メッセージを受け入れることができるhttp:// localhost:3922/Service1.svcでリッスンしているエンドポイントはありませんでした。これは多くの場合、誤ったアドレスまたはSOAPアクションが原因で発生します。詳細については、InnerException(存在する場合)を参照してください。

CookiesContainerオブジェクトをサービスからクライアントに返す方法がわかりません。誰かに教えてもらえますか?

4

2 に答える 2

1

他に何もない場合は、デバッグを支援するために、シリアル化を手動で実行します。CookieContainer は XmlSerializable ではありません (ただし、Soap Serializable であるため、実際には問題にはなりません)。

これが私の一般的なシリアル化メソッドです。おそらく、バイト配列をフィードするか、それConvert.ToBase64String()を返します。他に何もない場合でも、これにより、Web サービスが期待どおりに機能していることを完全に確認できます。

私が以下に持っている方法を使用して:

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

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

-

void svc_Get_Connected(object send, GetConnectCompletedEventArgs e)
{
    CookieContainer con = DeserializeObject<CookieContainer >(e.Result);
}

-

public static byte[] SerializeObject<T>(T obj)
{
    try
    {
        using (MemoryStream memoryStream = new MemoryStream())
        {
            BinaryFormatter xs = new BinaryFormatter();
            xs.Serialize(memoryStream, obj);

            return memoryStream.ToArray();
        }
    }
    catch
    {
        return null;
    }
}
public static T DeserializeObject<T>(byte[] xml)
{
    BinaryFormatter xs = new BinaryFormatter();
    MemoryStream memoryStream = new MemoryStream(xml);
    return (T)xs.Deserialize(memoryStream);
}
于 2012-09-10T21:18:56.653 に答える
0

これを試してください:

  1. クライアント プロジェクトで、Service Referenceに移動し、右クリックして、Update Service Referenceをクリックします。サービス サイン (任意のメソッドまたはパラメーター) を変更するたびに、この参照を更新する必要があります。いくつかの変更を行った後、この手順を実行するのを忘れている可能性があります。

  2. 念のため、インターフェイスとサービスの定義で params 名を等しく設定してください。インターフェイスCookieContainer GetConnect(string uname, string password);で定義されていることに注意してください を指定しますが、Service1実装では を使用して宣言します。問題はありませんが、整理整頓のためです。string unameCookieContainer GetConnect(string uid, string password);string uid

于 2012-09-10T22:05:11.347 に答える