• 用Web api /Nancy 通过Owin Self Host简易实现一个 Http 服务器


    过去做 端游的Http 服务器 用的WebApi 或者Mvc架构,都是放在iis。。。而我已经是懒出一个地步,并不想去配iis,或者去管理iis,所以我很喜欢 Self host 的启动方式。

    C#做 http 有2个轻量级的框架, 一个是Nancy ,一个是 微软官方的Web Api 都可以通过owin self host 在应用程序中启动监听

    Web Api

    官方教程 :https://www.asp.net/web-api/overview/hosting-aspnet-web-api/use-owin-to-self-host-web-api

    新建一个控制台从程序 
    在Nuget控制台上 安装包 Install-Package Microsoft.AspNet.WebApi.OwinSelfHost 
    然后添加一个Owin Startup类 
    以往所有的配置都正常的放在Startup中进行配置就可以

    public class Startup
        {
            // This code configures Web API. The Startup class is specified as a type
            // parameter in the WebApp.Start method.
            public void Configuration(IAppBuilder appBuilder)
            {
                // Configure Web API for self-host. 
                HttpConfiguration config = new HttpConfiguration();
                config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
                config.Routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "api/{controller}/{id}",
                    defaults: new { id = RouteParameter.Optional }
                );
                appBuilder.UseWebApi(config);
            }
        } 
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    然后在Main 函数里面加入 WebApp.Start() 就会在SelfHost 上面运行你的Web Api,十分简洁

    class Program
        {
            static void Main(string[] args)
            {
                string baseAddress = "http://localhost:9000/";
                // Start OWIN host 
                using (WebApp.Start<Startup>(url: baseAddress))
                {
                    // Create HttpCient and make a request to api/values 
                    HttpClient client = new HttpClient();
                    var response =client.GetAsync(baseAddress + "api/home").Result;
                    Console.WriteLine(response);
                    Console.WriteLine(response.Content.ReadAsStringAsync().Result);
                    Console.ReadLine(); 
                }
                Console.ReadLine(); 
            }
        }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    尝试添加一个Controller

    public class HomeController : ApiController
        {
            // GET api/values 
            public IHttpActionResult Get()
            {
                return Ok(125);
            }
            // GET api/values/5 
            public string Get(int id)
            {
                return "value";
            }
            // POST api/values 
            public void Post([FromBody]string value)
            {
            }
            // PUT api/values/5 
            public void Put(int id, [FromBody]string value)
            {
            }
            // DELETE api/values/5 
            public void Delete(int id)
            {
            }
        } 
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25

    尝试运行的结果 
    这里写图片描述

    这里写图片描述

    Nancy

    Nancy是很多人都推荐的一个轻量级的Http 库,可以架在Mono,.net.core 上,也是开源 
    安装Nancy可以 Install-Package Nancy 
    而要 在SelfHost 监听则需要安装以下3个

    Install-Package Microsoft.Owin.Hosting
    Install-Package Microsoft.Owin.Host.HttpListener
    Install-Package Nancy.Owin
    • 1
    • 2
    • 3

    在OwinStartup中表明使用Nancy

    using Owin;
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.UseNancy();
        }
    }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    入口也是通过WebApp.Start(url)

    using Microsoft.Owin.Hosting;
    class Program
    {
        static void Main(string[] args)
        {
            var url = "http://+:8080";
            using (WebApp.Start<Startup>(url))
            {
                Console.WriteLine("Running on {0}", url);
                Console.WriteLine("Press enter to exit");
                Console.ReadLine();
            }
        }
    }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    来源: https://github.com/NancyFx/Nancy/wiki/Hosting-nancy-with-owin#katana—httplistener-selfhost 
    添加一个Module

    /// <summary>
       /// 发现
       /// 可以通过 Before 进行 安全的验证
       /// </summary>
       public class HomeModule : NancyModule
       {
           public HomeModule()
           {
               Get["/"] = x => "Hello";
               Get["/login"] = x => {  return "person name :" + Request.Query.name + " age : " + Request.Query.age; };
           }
       }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    运行结果 
    这里写图片描述 
    这里写图片描述

  • 相关阅读:
    python爬虫知识点总结(二十一)Scrapy中Spiders用法
    python爬虫知识点总结(二十)Scrapy中选择器用法
    python爬虫知识点总结(十九)Scrapy命令行详解
    python爬虫知识点总结(十八)Scrapy框架基本使用
    python爬虫知识点总结(十七)Scrapy框架安装
    python爬虫知识点总结(十六)PySpider框架概述和用法详解
    python爬虫知识点总结(十五)PySpider框架基本使用以及抓取TripAdvisor
    python爬虫知识点总结(十四)使用Redis和Flask维护Cookies池
    python爬虫知识点总结(十三)使用代理处理反扒抓取微信文章
    图像识别
  • 原文地址:https://www.cnblogs.com/twinhead/p/9193899.html
Copyright © 2020-2023  润新知