C# ASP.NET WebApi服务器搭建详解 - Win服务承载(Windows Service Hosting宿主)


参考文章:
C# ASP.NET WebApi服务器搭建详解 - IIS服务承载(IIS Hosting IIS宿主)
C# ASP.NET WebApi服务器搭建详解 - 自承载(Self Hosting)
搭建Win服务承载(Windows Service Hosting宿主)ASP.NET WebApi服务器操作步骤详解:
1. 在VS解决方案建立Windows服务项目 Project,改名为:CSFramework.WebAPI.Demo.WinServiceHosting

添加Windows 服务,改名为WebApiServer.cs

2. 添加Windows 服务后,在WebApiServer.cs 添加如下代码。
OnStart:启动服务。
OnStop:停止服务。
C# Code:
using Microsoft.Owin.Hosting;
using System;
using System.ServiceProcess;
namespace CSFramework.WebAPI.Demo.WinServiceHosting
{
partial class WebApiServer : ServiceBase
{
private IDisposable _server = null;
public WebApiServer()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
try
{
Log2Local.Instance.WriteInfo("C# ASP.NET WebApi服务器搭建详解 - 自承载(Self Hosting)");
string serverURL = "http://localhost:17999/";
Log2Local.Instance.WriteInfo("服务器地址:" + serverURL);
//#if (DEBUG)
// Debugger.Launch(); //运行调试模式
//#endif
_server = WebApp.Start<StartupAppBuilder>(url: serverURL);
Log2Local.Instance.WriteInfo("成功启动WebApiServer.");
}
catch (Exception ex)
{
Log2Local.Instance.WriteInfo("启动WebApiServer失败," + ex.Message);
}
}
protected override void OnStop()
{
try
{
if (_server != null) _server.Dispose();
base.OnStop();
Log2Local.Instance.WriteInfo("成功停止WebApiServer.");
}
catch (Exception ex)
{
Log2Local.Instance.WriteException("停止WebApiServer失败," + ex.Message);
}
}
}
}
//来源:C/S框架网(www.csframework.com) QQ:23404761
using Microsoft.Owin.Hosting;
using System;
using System.ServiceProcess;
namespace CSFramework.WebAPI.Demo.WinServiceHosting
{
partial class WebApiServer : ServiceBase
{
private IDisposable _server = null;
public WebApiServer()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
try
{
Log2Local.Instance.WriteInfo("C# ASP.NET WebApi服务器搭建详解 - 自承载(Self Hosting)");
string serverURL = "http://localhost:17999/";
Log2Local.Instance.WriteInfo("服务器地址:" + serverURL);
//#if (DEBUG)
// Debugger.Launch(); //运行调试模式
//#endif
_server = WebApp.Start<StartupAppBuilder>(url: serverURL);
Log2Local.Instance.WriteInfo("成功启动WebApiServer.");
}
catch (Exception ex)
{
Log2Local.Instance.WriteInfo("启动WebApiServer失败," + ex.Message);
}
}
protected override void OnStop()
{
try
{
if (_server != null) _server.Dispose();
base.OnStop();
Log2Local.Instance.WriteInfo("成功停止WebApiServer.");
}
catch (Exception ex)
{
Log2Local.Instance.WriteException("停止WebApiServer失败," + ex.Message);
}
}
}
}
//来源:C/S框架网(www.csframework.com) QQ:23404761
3. 给WebApiServer添加安装程序。
Windows服务需要安装服务才能启动的,不允许直接运行EXE程序的。

添加安装程序ProjectInstaller.cs

4. 安装程序设置服务名称、服务描述
C# Code:
[RunInstaller(true)]
public partial class ProjectInstaller : System.Configuration.Install.Installer
{
public ProjectInstaller()
{
InitializeComponent();
serviceInstaller1.ServiceName = "CSFramework.WebAPI.Demo.WinServiceHosting";
serviceInstaller1.DisplayName = "CSFramework.WebAPI服务器";
serviceInstaller1.Description = "CSFramework.WebAPI服务器,Windows服务承载(Hosting)";
}
}
//来源:C/S框架网(www.csframework.com) QQ:23404761
[RunInstaller(true)]
public partial class ProjectInstaller : System.Configuration.Install.Installer
{
public ProjectInstaller()
{
InitializeComponent();
serviceInstaller1.ServiceName = "CSFramework.WebAPI.Demo.WinServiceHosting";
serviceInstaller1.DisplayName = "CSFramework.WebAPI服务器";
serviceInstaller1.Description = "CSFramework.WebAPI服务器,Windows服务承载(Hosting)";
}
}
//来源:C/S框架网(www.csframework.com) QQ:23404761
5. WebApi核心StartupAppBuilder类,用于配置WebApi服务器参数。
C# Code:
public class StartupAppBuilder
{
public static void Configuration(IAppBuilder appBuilder)
{
// 在应用程序启动时运行的代码
//加载WebApi服务器配置信息
HttpConfiguration config = new HttpConfiguration();
//配置路由
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "ActionApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional });
Log2Local.Instance.WriteInfo("配置JSON格式化.");
//NuGet: Microsoft.Owin.Hosting;
GlobalConfiguration.Configuration.Formatters.Insert(0, new PlainTextTypeFormatter());
config.Formatters.JsonFormatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
config.Formatters.JsonFormatter.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm";
config.Formatters.JsonFormatter.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
config.Formatters.Remove(config.Formatters.XmlFormatter);
// 解决json序列化时的循环引用问题
config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
// 对 JSON 数据使用混合大小写。驼峰式,但是是javascript 首字母小写形式.
//config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
// 对 JSON 数据使用混合大小写。跟属性名同样的大小.输出
config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new UnderlineSplitContractResolver();
Log2Local.Instance.WriteInfo("添加消息监听处理器.");
config.MessageHandlers.Add(new RequestListenHandler(Log2Local.Instance));
//使用配置
appBuilder.UseWebApi(config);
appBuilder.UseStageMarker(PipelineStage.PostAcquireState);
//链接控制器
Type C1 = typeof(CSFramework.WebAPI.Demo.DemoController);
Log2Local.Instance.WriteInfo("配置完成.");
}
}
//来源:C/S框架网(www.csframework.com) QQ:23404761
public class StartupAppBuilder
{
public static void Configuration(IAppBuilder appBuilder)
{
// 在应用程序启动时运行的代码
//加载WebApi服务器配置信息
HttpConfiguration config = new HttpConfiguration();
//配置路由
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "ActionApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional });
Log2Local.Instance.WriteInfo("配置JSON格式化.");
//NuGet: Microsoft.Owin.Hosting;
GlobalConfiguration.Configuration.Formatters.Insert(0, new PlainTextTypeFormatter());
config.Formatters.JsonFormatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
config.Formatters.JsonFormatter.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm";
config.Formatters.JsonFormatter.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
config.Formatters.Remove(config.Formatters.XmlFormatter);
// 解决json序列化时的循环引用问题
config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
// 对 JSON 数据使用混合大小写。驼峰式,但是是javascript 首字母小写形式.
//config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
// 对 JSON 数据使用混合大小写。跟属性名同样的大小.输出
config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new UnderlineSplitContractResolver();
Log2Local.Instance.WriteInfo("添加消息监听处理器.");
config.MessageHandlers.Add(new RequestListenHandler(Log2Local.Instance));
//使用配置
appBuilder.UseWebApi(config);
appBuilder.UseStageMarker(PipelineStage.PostAcquireState);
//链接控制器
Type C1 = typeof(CSFramework.WebAPI.Demo.DemoController);
Log2Local.Instance.WriteInfo("配置完成.");
}
}
//来源:C/S框架网(www.csframework.com) QQ:23404761
6. 用于监听WebApi服务器所有请求的处理程序
C# Code:
/// <summary>
/// 监听WebAPI服务器所有请求.
/// </summary>
public class RequestListenHandler : DelegatingHandler
{
protected Log2Local _log;
public RequestListenHandler(Log2Local log)
{
_log = log;
}
protected override System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
{
//注意:若Request.Method=POST,不可读取Request.Body流(Stream)信息,一旦读取,会销毁Stream对象。
//Method=GET,读取RequestUri
//控制台显示请求的URI信息
_log.WriteInfo("收到请求:" + request.RequestUri);
//调用WebAPI控制器接口完毕,才执行下面的代码
return base.SendAsync(request, cancellationToken).ContinueWith((task) =>
{
//添加日志
_log.WriteInfo("StatusCode:" + (task.Result as HttpResponseMessage).StatusCode.ToString());
return task.Result;
});
}
}
//来源:C/S框架网(www.csframework.com) QQ:23404761
/// <summary>
/// 监听WebAPI服务器所有请求.
/// </summary>
public class RequestListenHandler : DelegatingHandler
{
protected Log2Local _log;
public RequestListenHandler(Log2Local log)
{
_log = log;
}
protected override System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
{
//注意:若Request.Method=POST,不可读取Request.Body流(Stream)信息,一旦读取,会销毁Stream对象。
//Method=GET,读取RequestUri
//控制台显示请求的URI信息
_log.WriteInfo("收到请求:" + request.RequestUri);
//调用WebAPI控制器接口完毕,才执行下面的代码
return base.SendAsync(request, cancellationToken).ContinueWith((task) =>
{
//添加日志
_log.WriteInfo("StatusCode:" + (task.Result as HttpResponseMessage).StatusCode.ToString());
return task.Result;
});
}
}
//来源:C/S框架网(www.csframework.com) QQ:23404761
7. 建立用于安装win服务的批处理命令, 以管理员身份运行 _安装服务.bat
_安装Win服务.bat
dos command:
path c:\windows\system32;
path %SystemRoot%\Microsoft.NET\Framework\v4.0.30319;
echo "开始卸载服务***************************"
installutil.exe /u %~d0%~p0CSFramework.WebAPI.Demo.WinServiceHosting.exe
echo "开始安装服务**************************"
installutil.exe %~d0%~p0CSFramework.WebAPI.Demo.WinServiceHosting.exe
echo "设置服务自动启动*********************"
sc config CSFramework.WebAPI.Demo.WinServiceHosting start= auto
Net Start CSFramework.WebAPI.Demo.WinServiceHosting
pause;
//来源:C/S框架网(www.csframework.com) QQ:23404761
path c:\windows\system32;
path %SystemRoot%\Microsoft.NET\Framework\v4.0.30319;
echo "开始卸载服务***************************"
installutil.exe /u %~d0%~p0CSFramework.WebAPI.Demo.WinServiceHosting.exe
echo "开始安装服务**************************"
installutil.exe %~d0%~p0CSFramework.WebAPI.Demo.WinServiceHosting.exe
echo "设置服务自动启动*********************"
sc config CSFramework.WebAPI.Demo.WinServiceHosting start= auto
Net Start CSFramework.WebAPI.Demo.WinServiceHosting
pause;
//来源:C/S框架网(www.csframework.com) QQ:23404761
8. 若安装win服务的时候弹出【设置服务登陆】对话框,需要把ServiceProcessInstaller组件Account属性设置为LocalService。重新编译,以管理员身份运行 _安装服务.bat。

9. 打开win服务管理器,查看当前服务器是否运行。
服务名称(对应Installer.ServiceName属性):CSFramework.WebAPI.Demo.WinServiceHosting
显示名称(对应Installer.DisplayName属性):CSFramework.WebAPI服务器
描述(对应Installer.Description属性):CSFramework.WebAPI服务器,Windows服务承载(Hosting)

10. 服务器启动成功后,在IE测试接口,输入 localhost:17999/api/demo/get

11. debug目录下的log.txt日志:
2020-02-17 21:14:38 | Info:C# ASP.NET WebApi服务器搭建详解 - 自承载(Self Hosting) | admin
2020-02-17 21:14:38 | Info:服务器地址:http://localhost:17999/ | admin
2020-02-17 21:14:38 | Info:配置JSON格式化. | admin
2020-02-17 21:14:39 | Info:添加消息监听处理器. | admin
2020-02-17 21:14:39 | Info:配置完成. | admin
2020-02-17 21:14:39 | Info:成功启动WebApiServer. | admin
2020-02-17 21:14:53 | Info:收到请求:http://localhost:17999/api/demo/get | admin
2020-02-17 21:14:53 | Info:StatusCode:OK | admin
2020-02-17 21:14:53 | Info:收到请求:http://localhost:17999/favicon.ico | admin
2020-02-17 21:14:53 | Info:StatusCode:NotFound | admin
....本文完....
.NET WebApi开发框架|MVC框架|后端框架|服务端框架-标准版V1.0




CSFramework.WebApi是服务端快速开发框架(后端框架),借助ASP.NET WebAPI底层架构的强大编程能力,封装成为可复用的以及可定制开发的服务端软件模板,CSFramework.WebApi提供可复用的软件架构和开发包,为用户快速轻松搭建基于HTTP协议、HTTPS协议以及支持多种客户端(如:APP、B/S、C/S、微信公众号、微信小程序等)各种跨平台移动终端的服务端应用程序。
服务端应用开发、后端接口开发是软件项目重要工作环节,服务端注重业务逻辑、数据处理和数据分析、算法等方面的设计和服务,前端主要体现在用户体验、界面操作和数据采集方面。前端软件系统和后端服务架构共同搭建跨平台大型数据管理应用系统。
扫一扫加微信:
版权声明:本文为开发框架文库发布内容,转载请附上原文出处连接
NewDoc C/S框架网