今天有在研究SignalR, 發現SignalR可以使用Self-Host的方式,就突發奇想,Web Api是不是也可以使用Self-Host的方式寄宿在Console Application或者其他的地方。
微軟MSDN上給出的詳細的答案,Web Api和WCF以及SignalR一樣,支援Self-Host。
建立Self-Host項目
建立Console Application

建立成功之後,使用Nuget引入Web Api和Owin包。
打開Package Manager Console, 在裡面錄入以下指令
Install-Package Microsoft.AspNet.WebApi.OwinSelfHost
配置Web API Self-Host
在解決方案管理視窗,右鍵點選項目,選擇Add/Class, 添加一個新檔案Startup.cs
在Startup.cs中添加Configuration方法,該方法中指定了目前項目啟用Web Api并指定了路由規則
using Owin;
using System.Web.Http;
namespace OwinSelfhostSample
{
public class Startup
{
// This code configures Web API. The Startup class is specified as a type
// parameter in the WebApp.Start method.
public void Configuration(IAppBuilder appBuilder)
{
// Configure Web API for self-host.
HttpConfiguration config = new HttpConfiguration();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
appBuilder.UseWebApi(config);
}
}
}
添加 Web Api Controller
在解決方案中,右鍵點選項目,選擇Add/Class, 添加ValuesController.cs
using System.Collections.Generic;
using System.Web.Http;
namespace OwinSelfhostSample
{
public class ValuesController : ApiController
{
// GET api/values
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/values/5
public string Get(int id)
{
return "value";
}
// POST api/values
public void Post([FromBody]string value)
{
}
// PUT api/values/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/values/5
public void Delete(int id)
{
}
}
}
使用Owin Host
修改Program.cs, 定義web api的base url, 并啟動Owin Host
using Microsoft.Owin.Hosting;
using System;
namespace SelfHost
{
class Program
{
static void Main(string[] args)
{
string baseAddress = "http://localhost:9000/";
// Start OWIN host
using (WebApp.Start<Startup>(url: baseAddress))
{
Console.WriteLine("App Server started.");
Console.ReadLine();
}
}
}
}
使用Postman測試Api
啟動解決方案,等待程式顯示”App Server Started.”
打開Postman輸入測試的Api Url, 即得到正确的結果。