WCF应用示例

经过一番努力,完成了WCF测试程序,权为读书笔记~

(但仍然存在一个bug:目标程序集不包含服务类型,可能需要调整此程序集的代码访问安全策略)

已经解决此bug,是新建项目时出错,未注意到

服务端:

新建一‘WCF服务库’ 项目

服务契约为:

namespace WcfHelloEmployeeHost
{
    // 注意: 如果更改此处的接口名称“IService1”,也必须更新 App.config 中对“IService1”的引用。
    [ServiceContract]
    public interface IHelloEmployee
    {
        [OperationContract]
        string HelloMyCallEmployee(string EmpID);

        [OperationContract]
        IList<DataSchema.EmployeeModel> GetEmployee(string EmpUpID, string EmpLowerID);    

        // 任务: 在此处添加服务操作
    }
  
}

 

接口实现:

namespace WcfHelloEmployeeHost
{
    // 注意: 如果更改此处的类名“IService1”,也必须更新 App.config 中对“IService1”的引用。
    public class HelloEmployee : IHelloEmployee
    {
     

        #region IHelloEmployee 成员

        public string HelloMyCallEmployee(string EmpID)
        {
            string rStr = string.Format("Receive message at{0}:{1}", DateTime.Now.ToString(), EmpID);
            Console.WriteLine(rStr);
            string conStr = "user=sa;password=mypassword;server=servername;database=hroa";
            SqlConnection con = new SqlConnection(conStr);
            SqlCommand cmd = new SqlCommand("select * from Hr_EmployeeInfo where EmpID=" + EmpID, con);
            if (con.State == ConnectionState.Closed)
                con.Open();
            SqlDataReader Reader = cmd.ExecuteReader();
            while (Reader.Read())
            {
                rStr = "返回处理结果为:用户名是--" + Reader["Name"].ToString();
            }
            Console.WriteLine(rStr);
            Reader.Close();
            Reader.Dispose();
            con.Close();
            cmd.Dispose();

            return rStr;
        }
        public IList<DataSchema.EmployeeModel> GetEmployee(string EmpUpID, string EmpLowerID)
        {
            IList<DataSchema.EmployeeModel> LST=new List<DataSchema.EmployeeModel>();
            string conStr = "user=sa;password=mypassword;server=servername;database=hroa";
            SqlConnection con = new SqlConnection(conStr);
            SqlCommand cmd = new SqlCommand("select * from hr_EmployeeInfo where Empid>=" + EmpLowerID + " and empid<=" + EmpUpID, con);
            SqlDataAdapter ap = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            ap.Fill(ds);
            for (int j = 0; j < ds.Tables[0].Rows.Count; j++)
            {
                DataRow dr = ds.Tables[0].Rows[j];
                DataSchema.EmployeeModel em = new DataSchema.EmployeeModel();
                em.Name = dr["Name"].ToString();
                em.EmpID = dr["EmpID"].ToString();
                LST.Add(em);
            }
            return LST;

        }
       

        #endregion
    }
}

//*特别说明,对于数组传递可利用IList<T> 其中T必须为数据契约类型;或数据契约数组类型数据

主机运行程序:

 internal static ServiceHost myServiceHost = null;
        internal static void StartService()
        {
            myServiceHost = new ServiceHost(typeof(HelloEmployee));
            myServiceHost.AddServiceEndpoint(typeof(IHelloEmployee), new WSHttpBinding(), "http://localhost:9002/MyEmployee");
            myServiceHost.Open();
        }
        internal static void StopService()
        {
            if (myServiceHost.State != CommunicationState.Closed)
                myServiceHost.Close();
        }

        static void Main(string[] args)
        {
            //using (ServiceHost host = new ServiceHost(typeof(HelloEmployee)))
            //{
            //    host.AddServiceEndpoint(typeof(IHelloEmployee), new WSHttpBinding(), "http://localhost:9002/MyEmployee");
            //    host.Open();
            //    Console.ReadLine();
            //}
            StartService();
            Console.WriteLine("the server is running ...");
            Console.ReadLine();
            StopService();

        }

服务器端app.config配置:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.web>
    <trust level="Full"/>
    <compilation debug="true" />
  </system.web>
  <!-- 部署服务库项目时,必须将配置文件的内容添加到
  主机的 app.config 文件中。System.Configuration 不支持库的配置文件。-->
  <system.serviceModel>
    <services>
      <service name="WcfHelloEmployeeHost.HelloEmployee"

(注:此处关联服务契约实现实例)

behaviorConfiguration="WcfHelloEmployeeHost.HelloEmployeeBehavior">
        <host>
          <baseAddresses>
            <add baseAddress = "http://localhost:8732/HelloEmployee" />

(注:此URI为服务监听地址,注意区别于服务器端点URi)
          </baseAddresses>
        </host>
        <!-- Service Endpoints -->
        <!-- 除非完全限定,否则地址将与上面提供的基址相关 -->
        <endpoint address ="" binding="wsHttpBinding" contract="WcfHelloEmployeeHost.IHelloEmployee">

(注:此处关联服务契约接口)
          <!--
              部署时,应删除或替换下列标识元素,以反映
              在其下运行部署服务的标识。删除之后,WCF 将
              自动推导相应标识。
          -->
          <identity>
            <dns value="localhost"/>
          </identity>
        </endpoint>
        <!-- Metadata Endpoints -->
        <!-- 元数据交换终结点由服务用于向客户端做自我描述。-->
        <!-- 此终结点不使用安全绑定,应在部署前确保其安全或将其删除-->
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="WcfHelloEmployeeHost.HelloEmployeeBehavior">
          <!-- 为避免泄漏元数据信息,
          请在部署前将以下值设置为 false 并删除上面的元数据终结点  -->
          <serviceMetadata httpGetEnabled="True"/>
          <!-- 要接收故障异常详细信息以进行调试,
          请将下值设置为 true。在部署前
            设置为 false 以避免泄漏异常信息-->
          <serviceDebug includeExceptionDetailInFaults="False" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
</configuration>
数据契约为:

namespace DataSchema
{
    [DataContract(Namespace="http://www.revencooa.com")]
    public class EmployeeModel
    {
        private string _Name;
        [DataMember]
        public string Name
        {
            get { return _Name; }
            set { _Name = value; }
        }
        private string _EmpID;
        [DataMember]
        public string EmpID
        {
            get { return _EmpID; }
            set { _EmpID = value; }
        }
    }
}

客户端程序:

static void Main(string[] args)
        {
            
            MyHelEmpInfo.HelloEmployeeClient proxy = new WcfHelloEmployeeClient.MyHelEmpInfo.HelloEmployeeClient();
            Console.WriteLine("please input a Emp's ID");
            string empid = Console.ReadLine();

            Console.WriteLine(proxy.HelloMyCallEmployee(empid));
            string empidup = Console.ReadLine();
            IList<DataSchema.EmployeeModel> al = proxy.GetEmployee(empidup, empid);
            
            for (int i = 0; i < al.Count; i++)
            {
                DataSchema.EmployeeModel em = al[i];
                Console.WriteLine("职员名字为:" + em.Name + " 职员ID:" + em.EmpID);
            }
            Console.ReadLine();

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值