WCF--建立简单的WCF服务
[ServiceContract]
public interface IService1
{
    [OperationContract]
    string GetData(int value);
    
    [Operation Contract]
    CompositeType GetDataUsingDataContract(CompositeType composite);
// TODO: Add your service operations here
}
 
// Use a data contract as illustrated in the sample below to add composite types to service operations.
[DataContract]
public class CompositeType
{
    bool boolValue = true;
    string stringValue = "Hello ";
    [DataMember]
    public bool BoolValue
    {
        get {return boolValue; }
        set {boolValue = value; }
    }
 
    [DataMember]
    public string StringValue
    {
        get {return stringValue; }
        set {string Value = value; }
    }
}还声明了数据契约CompositeType,以类的形式声明。包括两个数据成员BoolValue和StringValue。
public class Service1 : IService1
{
    public string GetData(int value)
    {
        return string.Format("You entered: {0}",value);
    }
 
    public CompositeType GetDataUsingDataContract(CompositeType composite)
    {
        if (composite== null)
        {
            throw new ArgumentNullException("composite");
        }
        if (composite.BoolValue)
        {
            composite.StringValue+= "Suffix";
        }
        return composite;
    }
}本例在VS2010下,通过Tools-WCF Service Configeration Editor工具生成。
<?xml version="1.0" encoding="utf-8"?把该App.config文件放在与WinFormproject的根文件夹下(与Form1.cs同一文件夹),还须要在VS中将该文件增加到project中。> <configuration> <system.serviceModel> <behaviors> <serviceBehaviors> <behavior name="NewBehavior0"> <serviceMetadata httpGetEnabled="true" httpGetUrl="http://localhost:8585/wcf1/metadata" /> </behavior> </serviceBehaviors> </behaviors> <services> <service behaviorConfiguration="NewBehavior0" name="WcfService1.Service1"> <endpoint address="" binding="basicHttpBinding" bindingConfiguration="" name="ep1" contract="WcfService1.IService1" /> <host> <baseAddresses> <add baseAddress="http://localhost:8585/wcf1" /> </baseAddresses> </host> </service> </services> </system.serviceModel> </configuration>
private void button1_Click(objectsender, EventArgs e)
{
    System.ServiceModel.ServiceHosthost =new System.ServiceModel.ServiceHost(typeof(WcfService1.Service1));
    host.Open();
    this.label1.Text= "opened";
}ServiceReference1.Service1Clientaa=newServiceReference1.Service1Client(); MessageBox.Show(aa.GetData(2));六、总结
 
                    
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号