1. 程式人生 > >.net WCF簡單例項

.net WCF簡單例項

最近看到網上招聘有許多都需要WCF技術的人員,我之前一直沒接觸過這個東西,以後工作中難免會遇到,所謂笨鳥先飛,於是我就一探究竟,便有了這邊文章。由於是初學WCF沒有深入研究其原理,只是寫了一個demo留著以後,如果哪裡寫的不對希望大佬們能指出批評。個人認為WCF類似於Web Services(類似,肯定是有區別的,至於啥區別可以搜搜資料),不多說了,接下來看我簡單實現的demo吧。

  WCF服務用於兩個不同專案中的呼叫,在這裡我舉例專案A呼叫WCF服務實現查詢資料功能。

第一步:建立資料庫,有點資料能展示出來就行。

Create database SalesLibrary    --建立庫

Create table SalesVolume        --建立表
(
    Id int,
    Num int,
    Product varchar(20)
)

第二步:建立儲存過程(可以沒有此步,只是方便查詢)。

create proc proc_ShowSalesVolume 
as
select * from dbo.SalesVolume 

第三步:建立一個WCF解決方案。

   刪除掉預設的Iservice1和Service1,建立自己的WCF服務名稱。

第四步:編寫WCF服務。

  在IsalesVolumeOperation介面中寫一個現實資料的方法ShowSalesVolume,一定要寫上[OperationContract],如若不寫外界無法對其進行呼叫。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Data;

namespace WCFServices
{
    // 注意: 使用“重構”選單上的“重新命名”命令,可以同時更改程式碼和配置檔案中的介面名“ISalesVolumeOperation”。
    [ServiceContract]   // 服務合同 即提供服務的介面或類
    public interface ISalesVolumeOperation
    { 

        [OperationContract] //服務契約   即提供服務的實現方法
        DataTable ShowSalesVolume();
    }
}

  在salesVolumeOperation中完善查詢的的過程以及需要返回的引數。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Data;
using System.Data.SqlClient;

namespace WCFServices
{
    // 注意: 使用“重構”選單上的“重新命名”命令,可以同時更改程式碼、svc 和配置檔案中的類名“SalesVolumeOperation”。
    // 注意: 為了啟動 WCF 測試客戶端以測試此服務,請在解決方案資源管理器中選擇 SalesVolumeOperation.svc 或 SalesVolumeOperation.svc.cs,然後開始除錯。
    public class SalesVolumeOperation : ISalesVolumeOperation
    {
        public DataTable ShowSalesVolume()
        {
            DataSet ds = new DataSet();
            SqlConnection con = new SqlConnection("data source=.;initial catalog=SalesLibrary;user id=sa;password=sa123");
            string sql = "proc_ShowSalesVolume";      //儲存過程名稱
            using (SqlCommand cmd = new SqlCommand(sql, con))
            {
                con.Open();
                cmd.CommandType = CommandType.StoredProcedure;

                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(ds);
            }
            return ds.Tables[0];
        }
    }
}

第五步:對WCF服務介面測試看看是否無誤。

  選中SalesVolumeOperation.svc右鍵在瀏覽器中檢視,然後複製其路徑。

  開啟測試工具SoapUI,將路徑複製到initial WSDL 然後在路徑結尾寫上?wsdl。

  接著開始進行測試:

  看來WCF服務沒有出現問題,那麼我們就開始建立第二個程式來訪問這個WCF服務。

第六步:建立ASP.NET Web 應用程式(和WCF不在同一個解決方案)。

  選擇空版本就行,然後右鍵服務-->新增服務引用-->高階-->新增web引用:

  然後在解決方案中就可以看到:

第七步:實現呼叫WCF服務。

  新建一個頁面用於展示資料,名為ShowData.aspx

前臺程式碼:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Repeater ID="Repeater1" runat="server">
            <ItemTemplate>
                <%#Eval("Id") %>
                <%#Eval("Num") %>
                <%#Eval("Product") %>
                <br />
            </ItemTemplate>
        </asp:Repeater>
    </div>
    </form>
</body>
</html>

後臺程式碼:

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

namespace WebUI
{
    public partial class ShowData : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
             if(!IsPostBack)
             {
                 GetSalesVolume();
             }
        }
        private void GetSalesVolume()
        {
            SalesVolumeOperation.SalesVolumeOperation sa = new SalesVolumeOperation.SalesVolumeOperation();     //例項化WCF介面
            DataTable dt = sa.ShowSalesVolume();        //介面下的方法
            List<SalesVolume> list = new List<SalesVolume>();
            SalesVolume sv;
            foreach(DataRow dr in dt.Rows)
            {
                sv = new SalesVolume();
                sv.Id = Convert.ToInt32(dr["Id"]);
                sv.Num = Convert.ToInt32(dr["Num"]);
                sv.Product = dr["Product"].ToString();
                list.Add(sv); 
            }
            Repeater1.DataSource = list;
            Repeater1.DataBind();

        }
    } 
    public class SalesVolume
    {
        public int Id { get; set; }
        public int Num { get; set; }
        public string Product { get; set; }
    }
}

最後頁面上的展示結果: