C# 无框架最简单的Http服务

直接引用到项目中的dll

WinHttpListenServer.dll

 

访问:

  1. url: http://{ip}:{port}/{class}/{method}

  2. method: post

  3. data: string

方法和列表介绍
TypeList列表内传入提供http服务的类,作为http服务的方法需要标注特性 [IsHttpAction] ,且为单入参[string],出参[string]
Init(int port)初始化提供服务的端口,默认开始服务
Start()开始服务
Stop()暂停服务

源码分享

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Runtime.Remoting.Contexts;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;

namespace WinHttpListenServer
{
    [AttributeUsage(AttributeTargets.Method)]
    public class IsHttpActionAttribute:Attribute
    {

    }
    public class HttpServer
    {
        
        /// <summary>
        /// 运行状态
        /// </summary>
        private bool IsRun = true;

        /// <summary>
        /// Http监听器
        /// </summary>
        private HttpListener listener;

        /// <summary>
        /// 可供运行的方法 【单入参:string  出参:string】
        /// </summary>
        public List<Type> TypeList = new List<Type>();

        /// <summary>
        /// 目前只处理Post请求
        /// </summary>
        /// <param name="port"></param>
        public void Init(int port)
        {
            listener = new HttpListener();
            listener.Prefixes.Add($"http://+:{port}/");
            listener.Start();
            // 委托请求处理方法
            listener.BeginGetContext(HandleReusltData, null);
        }

        /// <summary>
        /// 开始
        /// </summary>
        public void Start()
        {
            if (!IsRun)
            {
                IsRun = true;
                listener.Start();
                listener.BeginGetContext(HandleReusltData, null);
            }
        }

        /// <summary>
        /// 暂停
        /// </summary>
        public void Stop()
        {
            if (IsRun)
            {
                IsRun = false;
                listener.Stop();
            }
        }

        private void HandleReusltData(IAsyncResult result)
        {
            if (IsRun)
            {
                // 继续监听-异步
                listener.BeginGetContext(HandleReusltData, null);

                // 获取表头信息
                HttpListenerContext context = listener.EndGetContext(result);
                HttpListenerRequest request = context.Request;
                HttpListenerResponse response = context.Response;

                // 返回客户端表头信息
                context.Response.ContentType = "application/json;charset=UTF-8";
                context.Response.AddHeader("Content-type", "application/json");
                context.Response.ContentEncoding = Encoding.UTF8;
                response.StatusDescription = "404";
                response.StatusCode = 404;

                // 地址
                List<string> method = request.RawUrl.Split('/').ToList();

                // 不处理空白地址
                if (method.Count < 3)
                {
                    SendData(response, "HttpServer Error!");
                    return;
                }

                // 请求方式走向
                if (request.InputStream != null) // 不处理空数据
                {
                    List<Type> list = TypeList.Where(x => x.Name.Equals(method[1])).ToList();
                    if (list.Count == 0)
                    {
                        SendData(response, "HttpServer Error!");
                        return;
                    }
                    List<MethodInfo> methodInfoList = list.First().GetMethods().Where(x => x.Name.Equals(method[2])).ToList();

                    if (methodInfoList.Count == 0)
                    {
                        SendData(response, "HttpServer Error!");
                        return;
                    }

                    MethodInfo action = methodInfoList.First();

                    // 判断是否标注特性
                    var methodAttribute = (IsHttpActionAttribute)Attribute.GetCustomAttribute(action, typeof(IsHttpActionAttribute));
                    if(methodAttribute == null)
                    {
                        SendData(response, "HttpServer Error!");
                        return;
                    }

                    // 统一走post请求
                    if (request.HttpMethod == "POST")
                    {
                        ReceiveData(request, response, action, list.First());
                    }
                    else
                    {
                        SendData(response, "Post request not supported!");
                    }
                }
            }
        }

        /// <summary>
        /// 接收数据
        /// </summary>
        /// <param name="request"></param>
        /// <param name="response"></param>
        /// <param name="methodInfo">执行方法</param>
        /// <returns></returns>
        private void ReceiveData(HttpListenerRequest request, HttpListenerResponse response, MethodInfo methodInfo, Type type)
        {
            string data = null;
            try
            {
                // 获取数据
                List<byte> bytes = new List<byte>();
                byte[] byteStr = new byte[2048];
                int readLen = 0;
                int len = 0;
                do
                {
                    readLen = request.InputStream.Read(byteStr, 0, byteStr.Length);
                    len += readLen;
                    bytes.AddRange(byteStr);
                }while(readLen != 0);
                data = Encoding.UTF8.GetString(bytes.ToArray(), 0, len);

                // 数据处理
                object instance = Activator.CreateInstance(type);
                string result = methodInfo.Invoke(instance, new object[] { data }) as string;
                // 发送数据
                response.StatusDescription = "200";
                response.StatusCode = 200;
                SendData(response, result);
            }
            catch (Exception)
            {
                SendData(response, "HttpServer Error!");
            }
        }

        /// <summary>
        /// 发送数据
        /// </summary>
        /// <param name="response"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        private void SendData(HttpListenerResponse response, string msg)
        {
            byte[] bytes = Encoding.UTF8.GetBytes(msg);
            try
            {
                using (Stream stream = response.OutputStream)
                {
                    stream.Write(bytes, 0, bytes.Length);
                }
            }
            catch (Exception)
            {
            }
        }
    }
}

使用示例

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WinHttpListenServer;

namespace HttpApp
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }
        HttpServer server = new HttpServer();
        private void button1_Click(object sender, EventArgs e)
        {
            server.TypeList.Add(typeof(Test));
            server.Init(8081);
            MessageBox.Show("服务启动成功");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            server.Start();
            MessageBox.Show("开始服务");
        }

        private void button3_Click(object sender, EventArgs e)
        {
            server.Stop();
            MessageBox.Show("停止服务");
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WinHttpListenServer;

namespace HttpApp
{
    public class Test
    {
        [IsHttpAction]
        public string Send(string data)
        {
            return data;
        }
    }
}

效果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值