寄宿Web API 不一定需要IIS 的支持,我们可以采用Self Host 的方式使用任意类型的应用程序(控制台、Windows Forms 应用、WPF 应用甚至是Windows Service)作为宿主。
方法:
Nuget上安装Microsoft.AspNet.WebApi.SelfHost库
或者 OWIN来承载WebAPI服务
或者 引用:
System.Net.Http.dll
C:Program Files (x86)Microsoft ASP.NETASP.NET Web Stack 5Packages:
packagesMicrosoft.AspNet.WebApi.Core.5.2.3lib et45System.Web.Http.dll
packagesMicrosoft.AspNet.WebApi.SelfHost.5.2.3lib et45System.Web.Http.SelfHost.dll
packagesMicrosoft.AspNet.WebApi.Client.5.2.3lib et45System.Net.Http.Formatting.dll
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());
}