WebAPI 寄宿windowService

时间:2014-06-04 13:04:28   收藏:0   阅读:677
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.SelfHost;
using System.Web.Http.Routing;
using System.Web.Http.Dispatcher;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.IO;
using System.Configuration;
using System.ServiceModel;
/***********************************************************  
** 作者: dl 
** 创始时间:2014年4月21日
** 描述:
** windows服务 用于weipAPI 寄宿
************************************************************/
namespace Legal.Api.Service
{
    partial class LSHMobileService : ServiceBase
    {
        private HttpSelfHostServer _server;
        private HttpSelfHostConfiguration _config;
        public static readonly int port = Convert.ToInt32(ConfigurationManager.AppSettings["ServicePort"]);
        private static readonly string logPath = ConfigurationManager.AppSettings["LogPath"];
        private static readonly bool hasClientTest = Convert.ToBoolean( ConfigurationManager.AppSettings["hasClientTest"]);
        
        /// <summary>
        /// 服务初始化
        /// </summary>
        public LSHMobileService()
        {
            InitializeComponent();
            Uri urlBase = new UriBuilder("HTTP", Dns.GetHostName(), port).Uri; //获取本地地址绑定端口
            _config = new HttpSelfHostConfiguration(urlBase);
            _config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}", new { id = RouteParameter.Optional });
            _config.TransferMode = TransferMode.Streamed;
            _config.Formatters.XmlFormatter.SupportedMediaTypes.Clear(); //清除xml格式数据 返回json格式
            _config.Filters.Add(new ModelValidationFilterAttribute());//添加全局模型验证
            if (hasClientTest)
            {
                _config.MessageHandlers.Add(new MessageHandler());
            }
        }


        /// <summary>
        /// 启动服务
        /// </summary>
        /// <param name="args"></param>
        protected override void OnStart(string[] args)
        {
            try
            {
                Assembly.Load("Legal.Api.Controller,Version=1.0.0.0, PublicKeyToken=null");//必须 手动加载程序集
                _server = new HttpSelfHostServer(_config);
                _server.OpenAsync().Wait();
                WriteLog("服务启动时间:" + DateTime.Now.ToString());
            }
            catch (Exception ex)
            {
                _server.CloseAsync().Wait();
                _server.Dispose();
                string msg = "异常时间:" + DateTime.Now.ToString() + "---错误信息:" + ex.Message;
                WriteLog(msg);
            }
        }


        /// <summary>
        /// 停止服务
        /// </summary>
        protected override void OnStop()
        {
            _server.CloseAsync().Wait();
            _server.Dispose();
            WriteLog("服务停止时间:" + DateTime.Now.ToString());


        }


        /// <summary>
        /// 写入服务日志
        /// </summary>
        /// <param name="strMsg"></param>
        private void WriteLog(string strMsg)
        {
            using (FileStream fs = new System.IO.FileStream(logPath, System.IO.FileMode.Append))
            {
                using (StreamWriter sw = new StreamWriter(fs))
                {
                    sw.WriteLine(strMsg);
                }
            }
        }


    }


}

WebAPI 寄宿windowService,布布扣,bubuko.com

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!