2013-11-04 121 views
11

我有下面的代碼:如何以編程方式創建BasicHttpBinding?

BasicHttpBinding binding = new BasicHttpBinding(); 

Uri baseAddress = new Uri ("URL.svc"); 

EndpointAddress endpointAddress = new EndpointAddress (baseAddress); 

var myChannelFactory = new ChannelFactory<IMyInterface> (binding, endpointAddress); 

IMyInterface client = null; 

try 
{ 
    client = myChannelFactory.CreateChannel(); 
    var a = client.WsFunction ("XXXXXX");      
    ((ICommunicationObject)client).Close(); 
} 
catch 
{ 
    if (client != null) 
    { 
     ((ICommunicationObject)client).Abort(); 
    } 
} 

其中 「IMyInterface的」 是,我的WS實現接口。例如:

[ServiceContract] 
public interface IMyInterface 
{ 
    [OperationContract] 
    Result WsFunction1 (string param); 

    [OperationContract] 
    Result WsFunction2 (string param); 

    [OperationContract] 
    Result WsFunction3 (string param); 
} 

,並返回是這樣的:

[DataContract] 
public class Result 
{ 
    string a = ""; 
    string b = ""; 

    [DataMember] 
    public string A 
    { 
     get { return a; } 
     set { a = value; } 
    } 

    [DataMember] 
    public string B 
    { 
     get { return b; } 
     set { b = value; } 
    } 
} 

當我運行這段代碼時,我可以到達WS,但我永遠無法獲得結果填寫。

我在做什麼錯?

提前致謝!

+0

這不會編譯,小a是字符串類型,大a是bool類型。 –

+0

這是因爲我改變了名字......但實際上它編譯和WS收到消息......但我不能得到結果.. – Crasher

+0

結果名稱空間是一個問題的罪魁禍首,但我會從嗅探流量開始http調試器。 –

回答

8

通過BasicHttpBinding訪問服務的最簡單方法是從Silverlight實用程序應用程序SlSvcUtil.exe生成客戶端代碼。

SLsvcUtil.exe /directory:C:\users\me\Desktop http://URL.svc 

這應該在它生成的文件內創建一個MyInterfaceClient類。

然後在你的代碼,你可以這樣做:

var binding = new BasicHttpBinding() { 
    Name = "BindingName", 
    MaxBufferSize = 2147483647, 
    MaxReceivedMessageSize = 2147483647 
}; 

var endpoint = new EndpointAddress("URL.svc"); 

MyInterfaceClient client = new MyInterfaceClient(binding, endpoint); 

client.WSFunctionCompleted += (object sender, WSFunctionCompletedEventArgs e) => { 
    //access e.Result here 
}; 

client.WSFunctionAsync("XXXXXX"); 

您的里程可能會有所不同。讓我知道這個是否奏效。

+1

利用SvcUtil會產生類似的結果。但我認爲整個問題都是關於「手工」做的。 –

+0

我想它至少會讓他讀代碼來弄清楚。不過,我不明白他爲什麼需要不使用SvcUtil。 –

+0

猜猜這是我需要的!謝謝你Millie! – Crasher

1
var binding = new BasicHttpBinding(); 
     binding.ProxyAddress = new Uri(string.Format("http://{0}:{1}", proxyAddress, proxyPort)); 
     binding.UseDefaultWebProxy = false; 
     binding.Security.Mode = BasicHttpSecurityMode.Transport; 
     binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None; 
     binding.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.Basic; 

     var endpoint = new EndpointAddress("serviceadress"); 

     var authenticationClient = new WOKMWSAuthenticateClient(binding, endpoint); 
     authenticationClient.ClientCredentials.UserName.UserName = username; 
     authenticationClient.ClientCredentials.UserName.Password = password; 

如果你想運行它在你的本地你應該這個代碼。

ServicePointManager.Expect100Continue = false;