先建立wcf类库.会默认生成一些试用代码.如下:
{
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