先建立wcf類庫.會預設生成一些試用代碼.如下: public class Service1 { public string GetData(int value) { return string.Format("You entered: {0}", value); } } 寄宿控制台.代碼如下 us ...
先建立wcf類庫.會預設生成一些試用代碼.如下:
public class Service1
{
public string GetData(int value)
{
return string.Format("You entered: {0}", value);
}
}
寄宿控制台.代碼如下
using System.ServiceModel;
using WcfServiceLibrary1;
ServiceHost serviceHost = new ServiceHost(typeof(Service1));
if (serviceHost.State != CommunicationState.Opened)
{
serviceHost.Open();
}
Console.WriteLine("WCF 服務正在運行......");
Console.WriteLine("輸入回車鍵 <ENTER> 退出WCF服務");
Console.ReadLine();
serviceHost.Close();
寄宿winform如下:
建立winform項目.會預設生成form1窗體
using System.ComponentModel;
using System.ServiceModel;
using WcfServiceLibrary1;
ServiceHost serviceHost = null;
BackgroundWorker worker = null;
public Form1()
{
InitializeComponent();
worker = new BackgroundWorker();
worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
worker.DoWork += new DoWorkEventHandler(worker_DoWork);
if (!worker.IsBusy)
{
worker.RunWorkerAsync();
}
}
void worker_DoWork(object sender, DoWorkEventArgs e)
{
try
{
serviceHost = new ServiceHost(typeof(Service1));
if (serviceHost.State != CommunicationState.Opened)
{
serviceHost.Open();
}
e.Result = "正常";
}
catch (Exception ex)
{
e.Result = ex.Message;
}
}
void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Result != null)
{
if (e.Result.ToString() == "正常")
{
tssTips.Text = "服務正在進行偵聽......";
}
else
{
tssTips.Text = string.Format("錯誤:{0}", e.Result);
}
lblTips.Text = tssTips.Text;
}
//錯誤處理
}
寄宿WindowService
添加WindowService類庫
Service1如下:
using System.ServiceModel;
using System.ServiceProcess;
protected override void OnStart(string[] args)
{
// TODO: 在此處添加代碼以啟動服務。
try
{
serviceHost = new ServiceHost(typeof(WcfServiceLibrary1.Service1));
if (serviceHost.State != CommunicationState.Opened)
{
serviceHost.Open();
}
}
catch (Exception ex)
{
//LogTextHelper.Error(ex);
}
// LogTextHelper.Info(Constants.ServiceName + DateTime.Now.ToShortTimeString() + "已成功調用了服務一次。");
//LogTextHelper.Info(Constants.ServiceName + "已成功啟動。");
}
/*
選中service1添加安裝程式
選中serviceProcessInstaller1組件,查看屬性,設置account為LocalSystem
選中serviceInstaller1組件,查看屬性
設置ServiceName的值, 該值表示在系統服務中的名稱
設置StartType, 如果為Manual則手動啟動,預設停止,如果為Automatic為自動啟動
設置Description,添加服務描述
點擊 開始,運行中輸入cmd,獲取命令提示符
win7需要已管理員的身份啟動,否則無法安裝
輸入 cd C:\Windows\Microsoft.NET\Framework\v4.0.30319 回車
切換當前目錄,此處需要註意的是,在C:\Windows\Microsoft.NET\Framework目錄下有很多類似版本,具體去哪個目錄要看項目的運行環境,例 如果是.net framework2.0則需要輸入 cd C:\Windows\Microsoft.NET\Framework\v2.0.50727
輸入 InstallUtil.exe D:\G工作\WCF寄宿WindowsService\WcfServiceLibrary1\windowsservice\bin\Debug\windowsservice.exe 回車
說明:D:\G工作\WCF寄宿WindowsService\WcfServiceLibrary1\windowsservice\bin\Debug\windowsservice.exe 示項目生成的exe文件位置
卸載很簡單,打開cmd, 直接輸入 sc delete WinServiceTest便可
*/
如果想要測試WCF是否正常運行
新建一個控制台程式.右鍵添加服務引用
ip地址在WCF類庫中如下:
<service name="WcfServiceLibrary1.Service1">
<host>
<baseAddresses>
<add baseAddress="http://localhost:8733/Design_Time_Addresses/WcfServiceLibrary1/Service1/" />
</baseAddresses>
</host>
接下來是WEBAPI的寄宿
WEBAPI相比WCF 前者是REST架構.後者是SOAP架構.在選擇宿主的時候就能看出WEBAPI的輕量級
新建控制台程式
nuget 安裝 SelfHost
static void Main(string[] args)
{
var config = new HttpSelfHostConfiguration("http://localhost:8080");
config.Routes.MapHttpRoute(
"API Default", "api/{controller}/{id}",
new { id = RouteParameter.Optional });
using (HttpSelfHostServer server = new HttpSelfHostServer(config))
{
server.OpenAsync().Wait();
Console.WriteLine("Press Enter to quit.");
Console.ReadLine();
}
}
public class Product
{
public string Name { get; set; }
public string Price { get; set; }
}
public class ProductsController : ApiController
{
static List<Product> products = new List<Product>() {
new Product(){Name="product1",Price="2.55"},
new Product(){Name="product2",Price="2.3"}
};
public IEnumerable<Product> Get()
{
return products;
}
}
運行之後可以通過地址欄調用或者Ajax
地址欄如下
http://localhost:8080/api/products/
在這裡.我們發現只要註冊路由.然後寫一個控制器.就可以完成WEBAPI的功能.非常輕盈
新建WindowsService服務
安裝SelfHost
using System.ServiceProcess;
using System.Web.Http;
using System.Web.Http.SelfHost;
在WindowService.Service中代碼如下:
public partial class Service1 : ServiceBase
{
private HttpSelfHostServer _server;
private readonly HttpSelfHostConfiguration _config;
public const string ServiceAddress = "http://localhost:1345";
public Service1()
{
InitializeComponent();
_config = new HttpSelfHostConfiguration(ServiceAddress);
_config.Routes.MapHttpRoute("DefaultApi",
"api/{controller}/{id}",
new { id = RouteParameter.Optional });
}
protected override void OnStart(string[] args)
{
#region Web Api監聽
_server = new HttpSelfHostServer(_config);
_server.OpenAsync();
#endregion
}
protected override void OnStop()
{
_server.CloseAsync().Wait();
_server.Dispose();
}
public class ApiServiceController : ApiController
{
[HttpGet]
public string Get()
{
return "Hello from windows service!";
}
}
}
http://localhost:1345/api/products/ApiService