WCF 学习

https://www.cnblogs.com/iamlilinfeng/archive/2012/09/25/2700049.html

using System.ServiceModel;

namespace WCFService {

    [ServiceContract]    

   public interface IUser    

    {        

        [OperationContract]        

       string ShowName(string name);    

} }

namespace WCFService {    

    public class User : IUser    

   {        

         public string ShowName(string name)       

        {            

             string wcfName = string.Format("WCF服务,显示姓名:{0}", name);             return wcfName;        

          }    

     }

}

大家可以看到,在WCF中的接口与普通接口的区别只在于两个上下文,其他的和我们正常学习的接口一样。定义这个上下文要添加System.ServiceModel的引用。

[ServiceContract],来说明接口是一个WCF的接口,如果不加的话,将不能被外部调用。

[OperationContract],来说明该方法是一个WCF接口的方法,不加的话同上。 

此时我们的第一个WCF服务程序就建立好了,将User.svc“设为起始页”,然后F5运行一下试试,如下图所示,VS2010自动调用了WCF的客户端测试工具以便我们测试程序:

五、将WCF程序寄宿在B服务器的IIS之上

  首先我们将WCF应用程序发布一下,然后部署在B服务器的IIS之上,如下图所示:

鼠标右键浏览Uesr.svc,在游览器中出现如下图所示,说明服务部署成功。

六、在客户端[A服务器]创建服务的引用

  我们这里以Web应用程序为例,建立地物理地址为本机,但是大家可以想像成B服务器是远程计算机,localhost为一个其他的IP地址。

  新建解决方案,并且创建ASP.NET Web应用程序的项目。命名为:WCFClient,如下图所示:

 、使用WCF服务端的方法

  WcfTest.aspx的代码如下:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WCFTest.aspx.cs" Inherits="WCFClient.WCFTest" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server">     <title></title> </head> <body>    

<form id="form1" runat="server">    

<asp:TextBox ID="txtName" runat="server"></asp:TextBox><br />    

<asp:Button ID="btnSubmit" runat="server" Text="测试WCF服务" OnClick="btnClick" />    

</form>

</body>

</html>

using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls;

//引用WCF服务的名称空间 using WCFClient.WCFService;

namespace WCFClient

{    

public partial class WCFTest : System.Web.UI.Page    

{        

protected void Page_Load(object sender, EventArgs e)        

{

  }

  protected void btnClick(object sender, EventArgs e)        

{            

   UserClient user = new UserClient();            

    string result = user.ShowName(this.txtName.Text);           

     Response.Write(result);        

}    

}

}

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