宿主一詞我們不會陌生,它可以看作是一個基礎設施,它為一些服務和功能提供最底層的支持,如你的web應用程序可以運行在iis或者apache上,而這兩個東西就是web應用程序的宿主,而今天說的自主宿主SelfHost就是說,它可以自己去監聽自己的服務,如你可以把一個web應用程序宿主到一個console控制台程序上,或者把一個webApi宿主到一個console或者windowService上,這都是可以的。
一 需要添加一些程序集引用
二 代碼實現
#region Web Api監聽
Assembly.Load("Lind.DDD.TestApi"); //手工加載某個api程序集的controller var config = new HttpSelfHostConfiguration("http://localhost:3333"); config.Routes.MapHttpRoute("default", "api/{controller}/{id}", new { id = RouteParameter.Optional }); var server = new HttpSelfHostServer(config); server.OpenAsync().Wait(); Console.WriteLine("Server is opened"); #endregion
三 web api代碼
/// <summary> /// 測試webapi /// </summary> public class TestController : ApiController { // GET api/<controller> public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; } // GET api/<controller>/5 public string Get(int id) { return "value"; } // POST api/<controller> public void Post([FromBody]Demo value) { Thread.Sleep(10000); Logger.Core.LoggerFactory.Instance.Logger_Info(value.ToString()); } // PUT api/<controller>/5 public void Put(int id, [FromBody]string value) { } // DELETE api/<controller>/5 public void Delete(int id) { } } public class Demo { public string appName { get; set; } public string url { get; set; } public override string ToString() { return string.Format("appName:{0},url:{1},datetime:{2}", this.appName, this.url, DateTime.Now); } }