寄宿Web API 不必定須要IIS 的支持,咱們能夠採用Self Host 的方式使用任意類型的應用程序(控制檯、Windows Forms 應用、WPF 應用甚至是Windows Service)做爲宿主。api
方法:ui
Nuget上安裝Microsoft.AspNet.WebApi.SelfHost庫orm
或者 OWIN來承載WebAPI服務server
或者 引用:get
System.Net.Http.dllstring
C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET Web Stack 5\Packages:it
packages\Microsoft.AspNet.WebApi.Core.5.2.3\lib\net45\System.Web.Http.dllio
packages\Microsoft.AspNet.WebApi.SelfHost.5.2.3\lib\net45\System.Web.Http.SelfHost.dllform
packages\Microsoft.AspNet.WebApi.Client.5.2.3\lib\net45\System.Net.Http.Formatting.dllclass
Newtonsoft.Json
例如控制檯:
public class ValuesController : ApiController
{
public IEnumerable<string> Get()
{
return new string[] { "111", "222" };
}
}
class Program
{
static void Main(string[] args)
{
//Assembly.Load("WebApplication1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"); //加載外部程序集
var config = new HttpSelfHostConfiguration("http://localhost:8080");
config.Routes.MapHttpRoute(
"API Default", "api/{controller}/{id}",
new { id = RouteParameter.Optional });
using (var server = new HttpSelfHostServer(config))
{
server.OpenAsync().Wait();
Console.WriteLine("Press Enter to quit.");
Console.ReadLine();
}
}
}
winform:
using (var server = new HttpSelfHostServer(config))
{
server.OpenAsync().Wait();
//Console.WriteLine("Press Enter to quit.");
//Console.ReadLine();
Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); }