快速创建简单的WCF跨平台服务

  废话在先:个人认为,对于有一定编程基础或有一定编程经验的开发者来说,学习新的技术并不喜欢看一些基础的介绍,也不需要花上多少时间,只需要看上几个简单明了的Demo,基本上就能明白其中的大概。最近在学习WCF编程,由于习惯于 http://DomainName/Service/Method?value=XXX 这种方式在客户端发送请求,于是想使用WCF实现这种请求服务,于是在网上寻找实现方式,然而找出的文章却尽是些介绍WCF原理废话(个人认为),却没有一个完整的Demo,于是就自己一番折腾~~

  本文针对于有一定asp.net或C/S开发基础的开发者,就不废话了,讲一下如何实现吧:

一、创建WCF服务应用程序: 

  

  啥?否知道这个界面在哪?呃~~还是先学一下asp.net基础吧~~

  创建后的项目结构如下:

  

  首先修改一下IService1.cs,需要被远程请求的方法都需要加上[OperationContract]特性,为了使用该方法能像网址一样的试调用,还需要添加如下特性:

1 [WebInvoke(
2             BodyStyle = WebMessageBodyStyle.WrappedRequest, 
3             RequestFormat = WebMessageFormat.Xml, 
4             ResponseFormat = WebMessageFormat.Json, 
5             Method = "GET", 
6             UriTemplate = "/GetData/{value}")]

  还是解释一下吧:

    RequestFormat: 这个是用于设置请求的数据用何种数据格式发送到服务器,可以是 WebMessageFormat.Xml 或 WebMessageFormat.Json;

  ResponseFormat: 这个是用于设置于响应的数据用何种数据格式返回给客户端:可以是 WebMessageFormat.Xml 或 WebMessageFormat.Json;

  Method:请求方式,可以是GET 或 POST;

  UriTemplate:这个是重点,就是请求地址的格式模板。

  先看一下IService1完整代码:

  [ServiceContract]
    public interface IService1
    {

        [OperationContract]
        [WebInvoke(
            BodyStyle = WebMessageBodyStyle.WrappedRequest, 
            RequestFormat = WebMessageFormat.Xml, 
            ResponseFormat = WebMessageFormat.Json, 
            Method = "GET", 
            UriTemplate = "/GetData/{value}")]
        string GetData(string value);

        [OperationContract]
        [WebInvoke(
            BodyStyle = WebMessageBodyStyle.WrappedRequest, 
            RequestFormat = WebMessageFormat.Json, 
            ResponseFormat = WebMessageFormat.Json, 
            Method = "GET", 
            UriTemplate = "/GetAge?age={age}")]
        string GetAge(string age);

        [OperationContract]
        CompositeType GetDataUsingDataContract(CompositeType composite);

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

  还是再简单讲一UriTemplate,如果你的请求地址模板是UriTemplate = "/GetData/{value}"  是酱紫滴~~那么请求的地址就是:

  http://DomainName/Service1.svc/Service1.svc/GetData/123

  如果请求地址模板是UriTemplate = "/GetAge?age={age}"  是酱紫滴~~那么请求的地址就是:

  http://localhost:27449/Service1.svc/GetAge?age=123

  特别注意的是,地址地板里的{} 的内容必需要跟方法的参数名一样。

  以上都是只有一个参数的,如果有多个参数,咋办呢?比如这样的方法:

  string Login(string userName,string pwd);

  猜到了吧,请求地址模板是酱紫:UriTemplate = "/Login?userName={userName}&password={pwd}",完整请求地址:

  http://localhost:27449/Service1.svc/Login?userName={Dincat}&password={123456}

  接下来看一下实现IService接口的类是咱样滴:

 1   [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
 2     public class Service1 : IService1
 3     {
 4         public string GetData(string value)
 5         {
 6             //WebOperationContext.Current.IncomingRequest.he
 7             return string.Format("You entered: {0}", value);
 8         }
 9 
10         public string GetAge(string age)
11         {
12             return string.Format("Your Age: {0}", age);
13         }
14 
15         public CompositeType GetDataUsingDataContract(CompositeType composite)
16         {
17             if (composite == null)
18             {
19                 throw new ArgumentNullException("composite");
20             }
21             if (composite.BoolValue)
22             {
23                 composite.StringValue += "Suffix";
24             }
25             return composite;
26         }
27     }

  这里不多讲,在类名上记得加上

  [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]

  就O了。 

  最后,把Web.config里的<system.serviceModel></system.serviceModel>节点修改一下,整个Web.config如下:

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <configuration>
 3 
 4   <system.web>
 5     <compilation debug="true" targetFramework="4.0" />
 6   </system.web>
 7 
 8   
 9   <system.serviceModel>
10     <services>
11       <service name="WcfService4.Service1" behaviorConfiguration="WcfService4.Service1Behavior">
12         <!-- Service Endpoints -->
13         <endpoint address="" binding="webHttpBinding" contract="WcfService4.IService1" behaviorConfiguration="httpBehavior">
14           <identity>
15             <dns value="localhost"/>
16           </identity>
17         </endpoint>
18         <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
19       </service>
20     </services>
21     <behaviors>
22       <serviceBehaviors>
23         <behavior name="WcfService4.Service1Behavior">
24           <!-- 为避免泄漏元数据信息,请在部署前将以下值设置为 false -->
25           <serviceMetadata httpGetEnabled="true" />
26           <!-- 要接收故障异常详细信息以进行调试,请将以下值设置为 true。在部署前设置为 false 以避免泄漏异常信息 -->
27           <serviceDebug includeExceptionDetailInFaults="true"/>
28 
29         </behavior>
30       </serviceBehaviors>
31 
32       <endpointBehaviors>
33         <behavior name="httpBehavior">
34           <webHttp/>
35         </behavior>
36       </endpointBehaviors>
37 
38     </behaviors>
39   </system.serviceModel>
40   
41   
42   <system.webServer>
43     <modules runAllManagedModulesForAllRequests="true"/>
44     <!--
45         若要在调试过程中浏览 Web 应用程序根目录,请将下面的值设置为 True。
46         在部署之前将该值设置为 False 可避免泄露 Web 应用程序文件夹信息。
47       -->
48     <directoryBrowse enabled="true"/>
49   </system.webServer>
50 
51 </configuration>

  好吧~~看不懂是吧?这里俺承认还是要看一下相关的基础,了解一下啥是Address(地址)、Binding(绑定)、Contract(契定)

  个人觉得这里比较关键的是 binding="webHttpBinding" ,这个设置用于设定你的服务用何种方式(命名管道、TCP、UDP、HTTP等等)来承载。

  另外一个关键点就是终点行为节点,看图:   

  

  如果没有上图的结点行为配置,看一下效果是咋滴:

  

  俺就是被这问题折腾了很久……

  好了,最后看一下运行效果吧:

  

源码地址:http://download.csdn.net/detail/dincat/9150205

原文地址:https://www.cnblogs.com/Dincat/p/Dincat.html