zoukankan      html  css  js  c++  java
  • 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序列化教程
  • 相关阅读:
    朴素贝叶斯分类-实战篇-如何进行文本分类
    朴素贝叶斯分类-理论篇-如何通过概率解决分类问题
    数据变换-归一化与标准化
    你还不懂傅里叶变换,那就过来掐死我吧
    Python快速入门 ---- 系列文章
    批处理中的时间计算详解
    使用electron+vue开发一个跨平台todolist(便签)桌面应用
    文科妹子都会用 GitHub,你这个工科生还等什么
    如约而至,.NET 5.0 正式发布
    如何进行正确的沟通?
  • 原文地址:https://www.cnblogs.com/wfpanskxin/p/12920455.html
Copyright © 2011-2022 走看看