WCF服务编程基础学习系列(一)
WCF学习正式开始了,今天看了一些资料做了一个Simple example.
第一步,创建我们的WCF服务运行库(WCFService Library)
1. 先创建一个服务接口,如:IUserService.cs,我们定义了两个成员方法(获取用户实体对象以及根据用户ID获取用户名称).
{
[OperationContract]
[FaultContract(typeof(UserFault))]
UserInfo GetUser(int id);
[OperationContract]
string GetUserNameById(int id);
}
注释:
ServiceContract 表示声明为WCF服务公共服务接口中一个公开成员接口.
OperationContract 表示声明为公开成员方法.
FaultContract(typeof(UserFault)) 表示该方法实现了错误契约,返回类型为"UserFault"类.
2. 紧接着创建实现服务契约接口的服务类,如:UserService.cs, 这里就说明了"WCF服务主要包含了interface类型的Contract和实现interface的类".
{
#region IUserService Members
public UserInfo GetUser(int id)
{
try
{
UserInfo info = new UserInfo();
info.Age = 16;
info.UserName = "YourName";
info.Location = "中国苏州";
info.Industry = "IT";
return info;
} catch (Exception e)
{
throw new FaultException<UserFault>(new UserFault(id, e.Message));
}
}
public string GetUserNameById(int id)
{
return "Benson";
}
#endregion
}
3. 创建实体类,其实应该优先于"服务契约实现类"创建的.
UserInfo.cs
[Serializable]
public class UserInfo
{
//[DataMember(Name = "Name")]
public string UserName
{
get;
set;
}
//[DataMember]
public int Age
{
get;
set;
}
//[DataMember]
public string Location
{
get;
set;
}
public string Industry
{
get;
set;
}
}
UserFault.cs
[Serializable]
public class UserFault
{
//[DataMember]
public string Message { get; set; }
//[DataMember]
public int UserId { get; set; }
public UserFault(int userId, string msg)
{
this.UserId = userId;
this.Message = msg;
}
}
注释: 关于这里的成员修饰标记 请到这里查看.
第二步,WCF服务运行库已经创建好了,下面开始启动这个服务,这里不多说了,直接看代码,我们创建了一个控制台程序项目(WCFStarter1). 如果服务启动异常 请看这里:
{
static void Main(string[] args)
{
using (ServiceHost host = new ServiceHost(typeof(UserService)))
{
host.Open();
Console.WriteLine("Service启动");
Console.ReadKey(true);
host.Close();
}
}
}
App.config
<configuration>
<system.web>
<compilation debug="true" />
</system.web>
<!-- When deploying the service library project, the content of the config file must be added to the host's
app.config file. System.Configuration does not support config files for libraries. -->
<system.serviceModel>
<services>
<service name="WcfServiceLibrary1.UserService" behaviorConfiguration="WcfServiceLibrary1.UserServiceBehavior">
<host>
<baseAddresses>
<add baseAddress = "http://localhost:8731/WcfServiceLibrary1/UserService/" />
</baseAddresses>
</host>
<!-- Service Endpoints -->
<!-- Unless fully qualified, address is relative to base address supplied above -->
<endpoint address ="" binding="wsHttpBinding" contract="WcfServiceLibrary1.IUserService">
<!--
Upon deployment, the following identity element should be removed or replaced to reflect the
identity under which the deployed service runs. If removed, WCF will infer an appropriate identity
automatically.
-->
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<!-- Metadata Endpoints -->
<!-- The Metadata Exchange endpoint is used by the service to describe itself to clients. -->
<!-- This endpoint does not use a secure binding and should be secured or removed before deployment -->
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="WcfServiceLibrary1.UserServiceBehavior">
<!-- To avoid disclosing metadata information,
set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="True"/>
<!-- To receive exception details in faults for debugging purposes,
set the value below to true. Set to false before deployment
to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="False" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
</configuration>
第三步,现在我们可以启动服务 并且创建我们的客户端了.同样是创建一个控制台程序项目(MyUserClient).
1. 启动WCF服务
2. 添加Service Reference, 输入刚才在App.config中配置的Service地址,如:http://localhost:8731/WcfServiceLibrary1/UserService/
点击GO, 修改我们的NameSpace,其他都默认,然后确定.
3. 调用WCF服务
{
static void Main(string[] args)
{
UserServiceClient client = new UserServiceClient();
UserInfo user = client.GetUser(1);
Console.WriteLine("姓名: " + user.UserNamek__BackingField);
Console.WriteLine("年龄: " + user.Agek__BackingField);
Console.WriteLine("地址: " + user.Locationk__BackingField);
Console.WriteLine("行业: " + user.Industryk__BackingField);
Console.ReadLine();
}
}
-------------------------------------------------
追逐梦想

浙公网安备 33010602011771号