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函数中写

using (var server = new RestServer())
{
    server.Start();
    Console.ReadLine();
    server.Stop();
}

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

[RestResource]
public class TestResource
{
    [RestRoute]
    public IHttpContext HelloWorld(IHttpContext context)
    {
        context.Response.SendResponse("Hello, world.");
        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";

https://github.com/sukona/Grapevine

猜你喜欢

转载自blog.csdn.net/v6543210/article/details/89574453