zoukankan      html  css  js  c++  java
  • 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来完成

  • 相关阅读:
    .Net中的AOP系列之《方法执行前后——边界切面》
    【信息学奥赛一本通】题解目录
    7219:复杂的整数划分问题
    1039 数的划分
    7215:简单的整数划分问题
    大整数阶乘的计算
    大数阶乘的位数和精确值计算【转】
    Window.Open详解
    在asp.net中显示PDF的方法:
    位运算技巧
  • 原文地址:https://www.cnblogs.com/fenger-VIP/p/6678667.html
Copyright © 2011-2022 走看看