c#基于HttpServerLite实现Http服务
侧边栏壁纸
  • 累计撰写 62 篇文章
  • 累计收到 23 条评论
C#

c#基于HttpServerLite实现Http服务

一缕清风
2021-03-01 / 2 评论 / 26 阅读 / 正在检测是否收录...

简介

之前开发的时候需要在winform中实现http服务,就想到了HttpListener来实现小型web服务器;但是我这人不是很喜欢用原生的HttpListener去实现本地web服务器,所以网上找了个开源的类库,用起来舒服点相比于HttpListener更加简单。本例子基于”HttpServerLite“实现。

首先我们从Nuget中安装”HttpServerLite“,然后编写代码。

winform中实现http服务

using HttpServerLite;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HttpServer
{
    class Program
    {
        /// <summary>
        /// WEB服务对象
        /// </summary>
        private static Webserver webserver;
        static void Main(string[] args)
        {
            if (webserver != null && webserver.IsListening)
            {
                Console.WriteLine("服务已启动...");
                return;
            }
            else
            {

                webserver = new Webserver("0.0.0.0", 80, DefaultRoute);
                webserver.Settings.Headers.Host = "http://0.0.0.0:80";
                webserver.Events.ServerStarted += ServerStarted;
                webserver.Events.ServerStopped += ServerStopped;
                webserver.Events.ServerDisposing += ServerDisposing;
                webserver.Events.Logger = Console.WriteLine;
                webserver.Settings.Debug.Responses = true;
                webserver.Settings.Debug.Routing = true;
                webserver.Start();
                Console.ReadKey();
            }
        }

        static void ServerStarted(object sender, EventArgs args) => Console.WriteLine("Http服务已启动");
        static void ServerStopped(object sender, EventArgs args) => Console.WriteLine("Http服务已停止");
        static void ServerDisposing(object sender, EventArgs args) => Console.WriteLine("Http服务已注销");


        /// <summary>
        /// 默认路由
        /// </summary>
        /// <param name="ctx"></param>
        /// <returns></returns>
        static async Task DefaultRoute(HttpContext ctx)
        {

            try
            {
                byte[] reqData = ctx.Request.Data;

                if (ctx.Request.Url.WithoutQuery.Equals("/"))
                {
                    string resp = "<html>" +
                " <head><title>HttpServerLite</title></head>" +
                " <body><h2>HttpServerLite</h2><p>HttpServerLite is running!</p></body>" +
                "</html>";
                    ctx.Response.StatusCode = 200;
                    ctx.Response.ContentType = "text/html";
                    await ctx.Response.SendAsync(resp);
                    return;
                }
                else
                {
                    ctx.Response.StatusCode = 404;
                    ctx.Response.ContentType = "text/plain";
                    ctx.Response.Send(true);
                    return;
                }
            }
            catch (Exception e)
            {
                ctx.Response.StatusCode = 500;
                ctx.Response.ContentType = "text/plain";
                ctx.Response.Send(e.ToString());
                Console.WriteLine(e.ToString());
                return;
            }
        }
        /// <summary>
        /// 简单GET接口
        /// </summary>
        /// <param name="ctx"></param>
        /// <returns></returns>

        [StaticRoute(HttpMethod.GET, "/api/GetServerTime")]
        public static async Task MyStaticRoute(HttpContext ctx)
        {
            ctx.Response.StatusCode = 200;
            ctx.Response.ContentType = "text/plain";
            await ctx.Response.SendAsync(DateTime.Now.ToString("yyyy-MM-dd HH:"));
            return;
        }

        /// <summary>
        /// 简单POST接口
        /// </summary>
        /// <param name="ctx"></param>
        /// <returns></returns>
        [ParameterRoute(HttpMethod.POST, "/api/Login")]
        public static async Task UserLogin(HttpContext ctx)
        {
            ctx.Response.StatusCode = 200;
            string json = Encoding.UTF8.GetString(ctx.Request.Data);

            ctx.Response.ContentType = "application/json";
            await ctx.Response.SendAsync("{\"code\":1000,\"msg\":\"操作成功\"}");
            return;
        }

        /// <summary>
        /// 参数路由
        /// </summary>
        /// <param name="ctx"></param>
        /// <returns></returns>

        [ParameterRoute(HttpMethod.GET, "/api/GetList/{id}")]
        public static async Task MyParameterRoute(HttpContext ctx)
        {
            ctx.Response.StatusCode = 200;
            ctx.Response.ContentType = "application/json";
            await ctx.Response.SendAsync("{\"code\":1000,\"msg\":\"传入的ID为{" + ctx.Request.Url.Parameters["id"] + "}\"}");
            return;
        }

        /// <summary>
        /// 动态路由
        /// </summary>
        /// <param name="ctx"></param>
        /// <returns></returns>
        [DynamicRoute(HttpMethod.GET, "^/api/\\d+$")]
        public static async Task MyDynamicRoute(HttpContext ctx)
        {
            string resp = "这是一个动态路由";
            ctx.Response.StatusCode = 200;
            ctx.Response.ContentType = "text/plain";
            await ctx.Response.SendAsync(resp);
            return;
        }
    }
}
0

评论 (2)

取消
  1. 头像
    申qy
    Windows 10 · Google Chrome

    没想到还是用到了这个,哈哈

    回复
  2. 头像
    sqz 作者
    Windows 10 · Google Chrome

    感谢博主分享

    回复