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

 

转载于:https://www.cnblogs.com/fenger-VIP/p/6678667.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值