• netcore3.x Request.Body 读取Body内容


    netcore2.0和3.0还是有很大的差异使用时请多注意:

    前提netcore3.0 默认不支持同步方法:ReadToEnd()

    使用时需要在Startup中添加:

     //默认不支持同步方法:ReadToEnd()
                services.Configure<KestrelServerOptions>(options =>
                {
                    options.AllowSynchronousIO = true;
                });
     #region BodyModel
            /// <summary>
            /// BodyModel
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="Request"></param>
            /// <returns></returns>
            public static T BodyModel<T>(this HttpRequest Request) where T : new()
            {
                T t = new T();
    
                try
                {
                    Request.EnableBuffering();  
                    using (Stream stream = Request.Body)
                    {
                        byte[] buffer = new byte[Request.ContentLength.Value];
                        stream.Read(buffer, 0, buffer.Length);
                        string content = Encoding.UTF8.GetString(buffer);
                Request.Body.Position = 0;
                        t = JsonSerializer.Deserialize<T>(content, JsonOpt.UnicodeRangesAll);
                    }
                }
                catch (Exception)
                {
                    t = default;
                }
                return t;
            }
    
            /// <summary>
            /// BodyModel
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="Request"></param>
            /// <returns></returns>
            public static async Task<T> BodyModelAsync<T>(this HttpRequest Request) where T : new()
            {
                T t = new T();
    
                try
                {
                    Request.EnableBuffering();
                    using (var reader = new StreamReader(Request.Body, Encoding.UTF8, true, 1024, true))
                    {
                        string body = await reader.ReadToEndAsync();
                        Request.Body.Position = 0;//以后可以重复读取
                        t = JsonSerializer.Deserialize<T>(body, JsonOpt.UnicodeRangesAll);
                    }
                }
                catch (Exception)
                {
                    t = default;
                }
                return t;
            }
            #endregion
    
            #region 多次获取Body内容
            /// <summary>
            /// 多次获取Body内容 
            /// 主要用于2.0时代 3.0时代弃用
            /// Request.EnableRewind();//2.0时代
            /// Request.EnableBuffering();//3.0时代
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="Request"></param>
            /// <returns></returns>
            public static T MulitBodyModel<T>(this HttpRequest Request) where T : new()
            {
                T t = new T();
                try
                {
                    Request.EnableBuffering();
                    using (var stream = new MemoryStream())
                    {
                        Request.Body.Position = 0;
                        Request.Body.CopyTo(stream);
                        string body = Encoding.UTF8.GetString(stream.ToArray());
                        t = JsonSerializer.Deserialize<T>(body, JsonOpt.UnicodeRangesAll);
                    }
                }
                catch (Exception)
                {
                    t = default;
                }
                return t;
            }
            #endregion
    
            #region GetBody
            /// <summary>
            /// GetBody
            /// </summary>
            /// <param name="Request"></param>
            /// <returns></returns>
            public static string GetBody(this HttpRequest Request)
            {
                string result = string.Empty;
                try
                {
                    Request.EnableBuffering();
                    using (Stream stream = Request.Body)
                    {
                        byte[] buffer = new byte[Request.ContentLength.Value];
                        stream.Read(buffer, 0, buffer.Length);
                        result = Encoding.UTF8.GetString(buffer);
                Request.Body.Position = 0;
                    }
                }
                catch (Exception) { }
                return result;
            }
    
            /// <summary>
            /// GetBody
            /// </summary>
            /// <param name="Request"></param>
            /// <returns></returns>
            public static async Task<string> GetBodyAsync(this HttpRequest Request)
            {
                string result = string.Empty;
                try
                {
                    Request.EnableBuffering();
                    using (var reader = new StreamReader(Request.Body, Encoding.UTF8, true, 1024, true))
                    {
                        result = await reader.ReadToEndAsync();
                        Request.Body.Position = 0;//以后可以重复读取
                    }
                }
                catch (Exception) { }
                return result;
            }
            #endregion
    
            #region GetFormModel
            /// <summary>
            ///  获取客户端搜索条件
            /// </summary>
            /// <param name="request"></param>
            /// <returns> </returns>
            public static T GetFormModel<T>(this HttpRequest request)
                where T : class, new()
            {
                T t = new T();
                Type type = t.GetType();
    
                try
                {
                    foreach (PropertyInfo property in type.GetProperties())
                    {
                        if (request.Form[property.Name].Count > 0)
                        {
                            property.SetValue(t, Convert.ChangeType((object)request.Form[property.Name][0], ConversionType.InitConversionType(property)), null);
                        }
                    }
                }
                catch (Exception)
                {
                    t = default;
                }
    
                return t;
            }
            #endregion

    使用方式:

    Person person3 = Request.BodyModel<Person>(); 

    参考资料:

    Request:  netcore HttpContext 自定义请求上下文内容

    微软自己的  序列化:

    System.Text.Json.dll
    JsonSerializer序列化教程
  • 相关阅读:
    入浅出MySQL 8.0 lock_sys锁相关优化 原创 腾讯数据库技术 腾讯数据库技术 2021-03-08
    以模型为中心,携程契约系统的演进
    bs
    外观模式
    设计接口时严格区分map、list,方便前端使用。
    t
    The HyperText Transfer Protocol (HTTP) 504
    入理解 epoll 原创 冯志明 Qunar技术沙龙 2021-03-10
    一次XSS和CSRF的组合拳进攻 (CSRF+JSON)
    当程序员具备了抽象思维 从码农到工匠 阿里巴巴中间件 2021-03-09
  • 原文地址:https://www.cnblogs.com/wfpanskxin/p/12920455.html
Copyright © 2020-2023  润新知