1.1.3 以Self Host方式寄宿Web API

  寄宿Web API不一定需要IIS的支持,我们可以采用Self Host的方式使用任意类型的应用程序(控制台、Windows Forms应用、WPF)作为宿主。

  对于SelfHost这样一个空的控制台应用来说,除了需要引用WebApi的项目,还需要引用以下程序集

      System.Web.Http

      System.Web.Http.SelfHost

      System.Net.Http

  对于Web Host的方式寄宿Web API需要做的唯一一件事情是路由注册。但是对于Self Host来说,除了必须的路由注册,我们还需要完成额外的一件事,

即手工加载定义了HttpController类型的程序集。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.SelfHost;

namespace SeifHost
{
    class Program
    {
        static void Main(string[] args)
        {
            Assembly.Load("WebApi, Version = 1.0.0.0, Culture = neutral, PublicKeyToken = null");

            HttpSelfHostConfiguration configuration = new HttpSelfHostConfiguration("http://localhost/selfhost");

            using (HttpSelfHostServer httpServer = new HttpSelfHostServer(configuration))
            {
                httpServer.Configuration.Routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "api/{controller}/{id}",
                    defaults: new { id = RouteParameter.Optional });
                httpServer.OpenAsync();
                Console.WriteLine("我已启动,亲可以在浏览器预览了。");
                Console.Read();
            }

        }
    }
}

 

我们启动程序 F5

 

 然后在浏览器输入http://localhost/selfhost/api/Contacts/001

 

 

   ASP.NET Web API的Self Host寄宿方式通过HttpSelfHostServer来完成

 

posted @ 2017-04-07 16:13  风儿_VIP  阅读(349)  评论(0编辑  收藏  举报