码迷,mamicode.com
首页 > Windows程序 > 详细

1.1.3 以Self Host方式寄宿Web API

时间:2017-04-07 16:48:34      阅读:279      评论:0      收藏:0      [点我收藏+]

标签:sem   param   1.0   image   contact   linq   还需要   log   open   

  寄宿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来完成

 

1.1.3 以Self Host方式寄宿Web API

标签:sem   param   1.0   image   contact   linq   还需要   log   open   

原文地址:http://www.cnblogs.com/fenger-VIP/p/6678667.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!