Self-Host

寄宿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()); }