Nancy如何接收POST过来的Json数据

当Nancy版本为2.0.0.0时

string postData = Request.Body.AsString;

当Nancy版本为1.4.5.0时

自己写一个扩展方法,代码如下

    /// <summary>
    /// Extensions for Stream
    /// </summary>
    public static class StreamExtensions
    {
        internal const int BufferSize = 4096;

        //
        // 摘要:
        //     Gets the request body as a string.
        // 参数:
        //   stream:
        //     The request body stream.
        //
        //   encoding:
        //     The encoding to use, System.Text.Encoding.UTF8 by default.
        //
        // 返回结果:
        //     The request body as a System.String.
        public static string AsString(this Stream stream, Encoding encoding = null)
        {
            using (StreamReader streamReader = new StreamReader(stream, encoding ?? Encoding.UTF8, true, BufferSize))
            {
                if (stream.CanSeek)
                {
                    long position = stream.Position;
                    stream.Position = 0L;
                    string result = streamReader.ReadToEnd();
                    stream.Position = position;
                    return result;
                }
            }
            return string.Empty;
        }
    }

使用

 string postData = Request.Body.AsString();

posted @   天天代码码天天  阅读(39)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示