- WCF 教程
- WCF - 主頁
- WCF - 概述
- WCF - 與 Web 服務對比
- WCF - 開發人員工具
- WCF - 體系結構
- WCF - 建立 WCF 服務
- WCF - 託管 WCF 服務
- WCS - IIS 託管
- WCF - 自我託管
- WCF - WAS 託管
- WCF - Windows 服務託管
- WCF - 使用 WCF 服務
- WCF - 服務繫結
- WCF - 例項管理
- WCF - 事務
- WCF - RIA 服務
- WCF - 安全性
- WCF - 異常處理
- WCF 資源
- WCF - 快速指南
- WCF - 有用資源
- WCF - 討論
WCF - 建立 WCF 服務
使用 Microsoft Visual Studio 2012 建立 WCF 服務是一項簡單的任務。以下是用於建立 WCF 服務的分步方法,包括所有必需的編碼,以便更深入地理解該概念。
- 啟動 Visual Studio 2012。
- 單擊“新建專案”,然後在 Visual C# 選項卡中選擇 WCF 選項。
建立了一個 WCF 服務,該服務執行諸如加法、減法、乘法和除法的基本算術運算。主程式碼位於兩個不同的檔案中 - 一個介面和一個類。
WCF 包含一個或多個介面及其實現類。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
namespace WcfServiceLibrary1 {
// NOTE: You can use the "Rename" command on the "Refactor" menu to
// change the interface name "IService1" in both code and config file
// together.
[ServiceContract]
Public interface IService1 {
[OperationContract]
int sum(int num1, int num2);
[OperationContract]
int Subtract(int num1, int num2);
[OperationContract]
int Multiply(int num1, int num2);
[OperationContract]
int Divide(int num1, int num2);
}
// Use a data contract as illustrated in the sample below to add
// composite types to service operations.
[DataContract]
Public class CompositeType {
Bool boolValue = true;
String stringValue = "Hello ";
[DataMember]
Public bool BoolValue {
get { return boolValue; }
set { boolValue = value; }
}
[DataMember]
Public string StringValue {
get { return stringValue; }
set { stringValue = value; }
}
}
}
其類的程式碼如下所示。
using System;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Runtime.Serialization;
usingSystem.ServiceModel;
usingSystem.Text;
namespace WcfServiceLibrary1 {
// NOTE: You can use the "Rename" command on the "Refactor" menu to
// change the class name "Service1" in both code and config file
// together.
publicclassService1 :IService1 {
// This Function Returns summation of two integer numbers
publicint sum(int num1, int num2) {
return num1 + num2;
}
// This function returns subtraction of two numbers.
// If num1 is smaller than number two then this function returns 0
publicint Subtract(int num1, int num2) {
if (num1 > num2) {
return num1 - num2;
}
else {
return 0;
}
}
// This function returns multiplication of two integer numbers.
publicint Multiply(int num1, int num2) {
return num1 * num2;
}
// This function returns integer value of two integer number.
// If num2 is 0 then this function returns 1.
publicint Divide(int num1, int num2) {
if (num2 != 0) {
return (num1 / num2);
} else {
return 1;
}
}
}
}
要執行此服務,請在 Visual Studio 中單擊“啟動”按鈕。
在執行此服務時,將出現以下螢幕。
單擊 sum 方法時,將開啟以下頁面。在此,您可以輸入任意兩個整數並單擊“呼叫”按鈕。該服務將返回這兩個數字的和。
與求和類似,我們可以執行選單中列出的所有其他算術運算。以下是它們的快照。
單擊減法方法時,將出現以下頁面。輸入整數,單擊“呼叫”按鈕,並獲取如下所示的輸出 -
單擊乘法方法時,將出現以下頁面。輸入整數,單擊“呼叫”按鈕,並獲取如下所示的輸出 -
單擊除法方法時,將出現以下頁面。輸入整數,單擊“呼叫”按鈕,並獲取如下所示的輸出 -
一旦呼叫服務,您就可以直接從此處在它們之間切換。
廣告