c/s端实现本地Http服务

之前开发c#的时候需要在winform中实现http服务,就想到了HttpListener来实现小型web服务器;但是我这人不是很喜欢用原生的HttpListener去实现本地web服务器,所以网上找了个开源的类库,用起来舒服点相比于HttpListener更加简单。本例子基于”HttpServerLite“实现。
首先,我们从Nuget中安装”HttpServerLite“,然后编写代码。
本地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;
        }
    }
}

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值