Self-Host

寄宿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.NET\ASP.NET Web Stack 5\Packages:

packages\Microsoft.AspNet.WebApi.Core.5.2.3\lib\net45\System.Web.Http.dll

packages\Microsoft.AspNet.WebApi.SelfHost.5.2.3\lib\net45\System.Web.Http.SelfHost.dll

packages\Microsoft.AspNet.WebApi.Client.5.2.3\lib\net45\System.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());
}

 

posted @ 2017-07-29 16:56  yuxiao  阅读(2791)  评论(0编辑  收藏  举报