wcf 数据服务,实现接口功能

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhangyatoua/article/details/50961518

            如果搜百度的话,是这么解释的:

   Windows Communication Foundation(WCF)是由微软开发的一系列支持数据通信的应用程序框架,可以翻译为Windows 通讯开发平台。
   整合了原有的windows通讯的 .net Remoting,WebService,Socket的机制,并融合有HTTPFTP的相关技术。

              但是      这篇文章介绍一下在wcf中如何使用get,post。

         1、服务端:

               首先在webconfig中进行改变:

              

<system.serviceModel>
    <bindings>
      <webHttpBinding>
        <binding name="webbinding"></binding>
      </webHttpBinding>
    </bindings>
    <services>
      <service name="Wcf1.Service1" behaviorConfiguration="testserviceBehavior">
        <endpoint address="" behaviorConfiguration="WebBehavior" binding="webHttpBinding" bindingConfiguration="webbinding" contract="Wcf1.IService1">
        </endpoint>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="testserviceBehavior">
          <!-- 为避免泄漏元数据信息,请在部署前将以下值设置为 false -->
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <!-- 要接收故障异常详细信息以进行调试,请将以下值设置为 true。在部署前设置为 false 以避免泄漏异常信息 -->
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="WebBehavior">
          <webHttp/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <protocolMapping>
        <add binding="basicHttpsBinding" scheme="https" />
    </protocolMapping>    
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>

              这里面进行改变的内容包括:services,behavior,endpointBehaviors

              后台代码:

               IService1.cs

     // 注意: 使用“重构”菜单上的“重命名”命令,可以同时更改代码和配置文件中的接口名“IService1”。
    [DataContractFormat]
    [ServiceContract]
    public interface IService1
    {
       [WebGet(UriTemplate = "/Service/GetData/{name}", BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json)]
        [OperationContract]
        string GetData(string name);


        [WebInvoke(Method = "POST", UriTemplate = "/Service/GetDataUsingDataContract", BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json)]
        [OperationContract]
        CompositeType GetDataUsingDataContract(CompositeType composite);


        // TODO: 在此添加您的服务操作
    }
                

               Service1.svc.cs中

 public class Service1 : IService1
    {
        public string GetData(string name)
        {
            return string.Format("You entered: {0}", name);
        }

        public CompositeType GetDataUsingDataContract(CompositeType composite)
        {
            if (composite == null)
            {
                throw new ArgumentNullException("composite");
            }
           
                composite.StringValue += "Suffix";
                composite.Name += "123";
          
            return composite;
        }
    }

                 单独封装了一个类CompositeType.cs

            

 [DataContract]
    public class CompositeType
    {
        [DataMember]
        public string StringValue
        {
            get;
            set;
        }
        [DataMember]
        public string Name
        {
            get;
            set;
        }
        bool boolValue = true;
        string stringValue = "Hello ";
    }

          2、客户端(新建的一个一般处理程序):

              Program中是这么写的

 static void Main(string[] args)
        {
            var rc = new Client("http://localhost:13048//Service1.svc");

            var uriget = string.Format("Service/GetData/{0}", "yatou");

            string retget = rc.get(uriget);
            Console.WriteLine(retget);

            const string uripost = "Service/GetDataUsingDataContract";
            string postdata = "{\"StringValue\":\"my name is zhangyatoua!\",\"Name\":\"yatou\"}";

            //const string postdata = "<CompositeType xmlns=\"http://rest-server/datacontract/CompositeType\"><StringValue>LV</StringValue></CompositeType>";

            var retpost = rc.Post(uripost, postdata);

            //var retpost = rc.JiekouPost();

            Console.WriteLine(retpost);

            Console.ReadLine();
        }

                 封装了一个单独的类Client.cs

public class Client
    {
       public Client(string baseuri)
       {
           _baseUri = baseuri;
       }

       private readonly string _baseUri;

       public string get (string uri)
       {
           var serverurl = string.Format("{0}/{1}", _baseUri, uri);
           var myRequest = (HttpWebRequest)WebRequest.Create(serverurl);

           string returnstr;
           using (var myResponse=(HttpWebResponse)myRequest.GetResponse())
           {
               using(var sr=new StreamReader(myResponse.GetResponseStream(),Encoding.UTF8))
               {
                   returnstr = HttpUtility.UrlDecode(sr.ReadToEnd());
                   sr.Close();
               }
               myResponse.Close();
           }
           return returnstr;
       }
       public string Post(string uri,string data)
       {
           var serverurl = string.Format("{0}/{1}", _baseUri, uri);

           var myRequest = (HttpWebRequest)WebRequest.Create(serverurl);

           var buf = Encoding.UTF8.GetBytes(data);

           myRequest.Method = "POST";
           myRequest.ContentLength = buf.Length;
           myRequest.ContentType = "text/json";

           using (var stream = myRequest.GetRequestStream())
           {
               stream.Write(buf, 0, buf.Length);
               stream.Close();
           }

           string returnstr;
           HttpWebResponse response;
           try
           {
               response = (HttpWebResponse)myRequest.GetResponse();
           }
           catch (WebException ex)
           {
               response = (HttpWebResponse)ex.Response;
           }
           // ReSharper disable once AssignNullToNotNullAttribute
           using (var sr = new StreamReader(response.GetResponseStream()))
           {
               returnstr = sr.ReadToEnd();
           }

           return returnstr;
       }

    }

             运行结果如下:


   第一行是get得到的,第二行是post得到的












阅读更多
换一批

没有更多推荐了,返回首页