契约Contract(ServiceContract、OperationContract、DataContract、ServiceKnownType和DataMember)

本文详细介绍了WCF(Windows Communication Foundation)中的各种契约概念,包括服务契约、操作契约、数据契约和服务已知类型等,并通过具体示例展示了如何在.NET框架下实现这些契约。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

介绍
WCF(Windows Communication Foundation) - 契约(Contract):服务契约(ServiceContract),操作契约(OperationContract),数据契约(DataContract),服务已知类型(ServiceKnownType),数据成员(DataMember)。


示例
1、服务
IPersonManager.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.ServiceModel;
using System.Runtime.Serialization;

namespace WCF.ServiceLib.Contract
{
    /// <summary>
    
/// 人员管理接口
    
/// </summary>

    // Namespace - 服务契约的命名空间
    
// Name - 服务契约的名称(会对应到相关的wsdl,默认情况下本例为接口名“IPersonManager”)
    
// ConfigurationName - 服务契约在宿主中所配置的服务名称(默认情况下本例为类的全名“WCF.ServiceLib.Contract.IPersonManager”)
    [ServiceContract(Namespace = "http://webabcd.cnblogs.com", Name = "IPersonManager", ConfigurationName = "ConfigurationNameTest")]
    // 服务已知类型 - Student(数据契约)继承自Person(数据契约),要指定Student为已知类型,其才会被序列化
    [ServiceKnownType(typeof(Student))]
    public interface IPersonManager
    {
        /// <summary>
        
/// 获取某人的姓名
        
/// </summary>
        
/// <param name="p">Person对象</param>
        
/// <returns></returns>

        // Name - 操作契约的名称(会对应到相关的wsdl,默认情况下本例为方法名“GetName”)
        [OperationContract(Name="GetPersonName")]
        string GetName([MessageParameter(Name = "person")] Person p);
    }

}

PersonManager.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.ServiceModel;
using System.Runtime.Serialization;

namespace WCF.ServiceLib.Contract
{
    /// <summary>
    
/// 人员管理类
    
/// </summary>

    public class PersonManager : IPersonManager
    {
        /// <summary>
        
/// 获取某人的姓名
        
/// </summary>
        
/// <param name="p">Person对象</param>
        
/// <returns></returns>

        public string GetName(Person p)
        {
             return "Name: " + p.Name;
        }

    }

}

Person.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.ServiceModel;
using System.Runtime.Serialization;

namespace WCF.ServiceLib.Contract
{
    /// <summary>
    
/// Person的实体类
    
/// </summary>

    // Name - 数据契约的名称(会对应到相关的wsdl,默认情况下本例为类名“Person”)
    [DataContract(Name = "PersonModel")]
    public class Person
    {
        /// <summary>
        
/// Person的实体类的Age属性
        
/// </summary>

        // Name - 数据成员的名称(会对应到相关的wsdl,默认情况下本例为属性名“Age”)
        
// IsRequired - 该值指示序列化引擎该成员在读取或反序列化时必须存在
        
// Order - 数据成员在相关的wsdl中的顺序
        
// EmitDefaultValue - 如果应该在序列化流中生成成员的默认值,则为 true,否则为 false,默认值为 true
        [DataMember(Name = "PersonAge", IsRequired = false, Order = 1)]
        public int Age getset; }

        /// <summary>
        
/// Person的实体类的Name属性
        
/// </summary>

        // Name - 数据成员的名称(会对应到相关的wsdl,默认情况下本例为属性名“Name”)
        
// IsRequired - 该值指示序列化引擎该成员在读取或反序列化时必须存在
        
// Order - 数据成员在相关的wsdl中的顺序
        
// EmitDefaultValue - 如果应该在序列化流中生成成员的默认值,则为 true,否则为 false,默认值为 true
        [DataMember(Name = "PersonName", IsRequired = false, Order = 0)]
        public string Name getset; }
    }

}


Student.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.ServiceModel;
using System.Runtime.Serialization;

namespace WCF.ServiceLib.Contract
{
    /// <summary>
    
/// Student的实体类
    
/// </summary>

    // Name - 数据契约的名称(会对应到相关的wsdl,默认情况下本例为类名“Student”)
    [DataContract(Name = "StudentModel")]
    public class Student : Person
    {
        /// <summary>
        
/// Student的实体类的School属性
        
/// </summary>

        // Name - 数据成员的名称(会对应到相关的wsdl,默认情况下本例为属性名“School”)
        
// IsRequired - 该值指示序列化引擎该成员在读取或反序列化时必须存在
        
// Order - 数据成员在相关的wsdl中的顺序
        
// EmitDefaultValue - 如果应该在序列化流中生成成员的默认值,则为 true,否则为 false,默认值为 true
        [DataMember(Name = "School", IsRequired = false, Order = 0)]
        public string School getset; }
    }

}



2、宿主
PersonManager.svc
<% @ ServiceHost Language="C#" Debug="true" Service="WCF.ServiceLib.Contract.PersonManager"  %>

Web.config
<? xml version="1.0" ?>
< configuration >
   < system .serviceModel >
     < behaviors >
       < serviceBehaviors >
         < behavior  name ="ContractBehavior" >
           <!-- httpGetEnabled - 使用get方式提供服务 -->
           < serviceMetadata  httpGetEnabled ="true"   />
         </ behavior >
       </ serviceBehaviors >
     </ behaviors >
     < services >
       <!-- name - 提供服务的类名 -->
       <!-- behaviorConfiguration - 指定相关的行为配置 -->
       < service  name ="WCF.ServiceLib.Contract.PersonManager"  behaviorConfiguration ="ContractBehavior" >
         <!-- address - 服务地址 -->
         <!-- binding - 通信方式 -->
         <!-- contract - 服务契约 -->
         < endpoint  address =""  binding ="basicHttpBinding"  contract ="ConfigurationNameTest"   />
       </ service >
     </ services >
   </ system.serviceModel >
</ configuration >


3、客户端
PersonManager.aspx
<% @ Page Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="PersonManager.aspx.cs"
    Inherits
="Contract_PersonManager" Title="契约(ServiceContract、OperationContract、DataContract、ServiceKnownType和DataMember)" 
%>

< asp:Content  ID ="Content1"  ContentPlaceHolderID ="head"  runat ="Server" >
</ asp:Content >
< asp:Content  ID ="Content2"  ContentPlaceHolderID ="ContentPlaceHolder1"  runat ="Server" >
     < asp:TextBox  ID ="txtName"  runat ="server"  Text ="webabcd"   />
     &nbsp;
     < asp:Button  ID ="btnGetName"  runat ="server"  Text ="GetName"  
        onclick
="btnGetName_Click"   />
</ asp:Content >

PersonManager.aspx .cs
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public  partial  class Contract_PersonManager : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }


    protected void btnGetName_Click(object sender, EventArgs e)
    {
        // Contract.IPersonManager pm = new Contract.PersonManagerClient();

        Contract.PersonManagerClient proxy = new Contract.PersonManagerClient();

        Contract.StudentModel sm = new Contract.StudentModel() { PersonName = txtName.Text };

        Page.ClientScript.RegisterStartupScript(
            this.GetType(),
            "js",
            string.Format("alert('{0}')", proxy.GetPersonName(sm)),
            true);

        proxy.Close();
    }

}


Web.config
<? xml version="1.0" ?>
< configuration >
   < system .serviceModel >
     < client >
       <!-- address - 服务地址 -->
       <!-- binding - 通信方式 -->
       <!-- contract - 服务契约 -->
       < endpoint  address ="http://localhost:3502/ServiceHost/Contract/PersonManager.svc"  binding ="basicHttpBinding"  contract ="Contract.IPersonManager"   />
     </ client >
   </ system.serviceModel >
</ configuration >


运行结果:
单击" btnGetName" 后弹出提示框,显示"Name: webabcd"
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值