03 Self Host方式寄宿WebAPI

来源:互联网 发布:淘宝价格走势图哪里看 编辑:程序博客网 时间:2024/05/13 12:23

(1) 启动VS2013,选择C#,新建空的控制台项目,项目名称SelfHost.

(2) 添加对上面Common库的引用。添加对System.web.http.dll的引用。具体位置在目录“%ProgramFiles%\MicrosoftASP.NET\ASP.NET Web Stack 5\Packages\”中。共4个添加:

System.Web.Http.dll(\Microsoft.AspNet.WebApi.Core.5.0.0\lib\net45\)

System.Net.Formatting.Http.dll(\Microsoft.AspNet.WebApi.Client.5.0.0\lib\net45\)

System.Web.Http.WebHost.dll(\Microsoft.AspNet.WebApi.WebHost.5.0.0\lib\net45\)

System.Net.Http.dll

 (3)修改代码如下:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Reflection;

using System.Runtime.CompilerServices;

using System.Runtime.InteropServices;

using System.Web.Http;

using System.Web.Http.SelfHost;

using System.Net.Http;

using System.Net.Http.Formatting;

using WebApi;

 

namespace SelfHost

{

    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.Read();

            }

        }

    }

}

(4) 右键点击SelfHost项目名称,选择“调试”,选择“启动新实例”。根据我们注册的路由,IE11,如果访问目标地址“http://localhost/selfhost/api/contacts”可以获得所有联系人列表;如果目标地址为“http://localhost/selfhost/api/contacts/001”,则可以得到ID 为“001”的联系人信息,得到Json格式,打开如下图。


0 0