Grapevine C# http server lib 的使用

Grapevine是一个比较好用的http server库,用C#语言实现。

底层基于C#的HttpListener,进行了一些封装。

非常适合用来写REST 风格的 json server

一、使用

最新的版本 NuGet上的是4.1.1.0版本发布 于 2017-8-22

具体使用:

1.Program.cs 的main函数中写

默认使用1234端口,可以修改成自定端口(此处是8080)。

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



using Grapevine.Server;
using Grapevine.Interfaces.Shared;


namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {


            using (var server = new RestServer())
            {
                server.Port = "8080";
                server.Start();
               // server.Logger. = LogLevel.Trace;
                Console.ReadLine();
                server.Stop();
            }


        }
    }
}


 2.加入一个路由,就是具体处理客户端的函数。

另新建一个.cs文件,加入以下内容即可。

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


using  Grapevine.Interfaces.Server;
using Grapevine.Server.Attributes;

[RestResource]
public class TestResource
{
    [RestRoute]
    public IHttpContext HelloWorld(IHttpContext context)
    {
        byte[] byteArray = System.Text.Encoding.Default.GetBytes(("Hello, world."));
        context.Response.SendResponse(byteArray);
        return context;
    }
}

参见作者的文档 https://sukona.github.io/Grapevine/en/getting-started.html

二、几个小坑

1. 用UTF-8解析客户端请求

如果客户端发送的json请求中带有中文,需要指定 charset=utf-8,底层Request.ContentEncoding;在无法解析charset时,默认会返回本地计算机的编码,一般是gbk,因此会导致解析出乱码。

解决办法就是下载源码,自行编译 https://github.com/sukona/Grapevine

修改Interface目录下HttpRequest.cs 

public string Payload
        {
            get
            {
                if (_payload != null) return _payload;
                using (var reader = new StreamReader(Request.InputStream, Encoding.UTF8))
                {
                    _payload = reader.ReadToEnd();
                }
                return _payload;
            }
        }

默认使用 UTF8编码进行解析。

2. 内部的ConsoleLogger

日期格式通过直接修改

public string DateFormat => @"yyyy-MM-dd hh:mm:ss.fff";

 

 

3.我的小例子

https://download.csdn.net/download/v6543210/12000095   访问localhost:8080/helloworld即可看到结果

 

官方的帮助位于:

https://sukona.github.io/Grapevine/en/

引用:

https://github.com/sukona/Grapevine

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

路边闲人2

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值