netcore Post Request 动态 接收请求数据 参数


一、PostMan 模拟POST请求

1.Form-data:

1.1.Headers=>Content-Type:multipart/form-data;  
1.2 Body=>form-data 添加请求参数

1.3netcore3 后端动态接收参数:

   ReqInfo reqInfo = Request.Model<ReqInfo>();

  

具体  Request.Model 在底下有

2.FormBody

2.1.Headers=>Content-Type:application/json 
2.2 Body=>raw json  添加请求对象

如:

{
    "Token":"EWL2324JLDJAJO3454J3J2J342LMRL2"
}

  

2.3  netcore3 后端动态接收参数:

   ReqInfo reqInfo = Request.Model<ReqInfo>();

  

二、
1.Ajax 请求form-data数据:
contentType
说是 $.ajax 设置数据类型 applicaiton/json之后,服务器端(express)就拿不到数据
$.ajax contentType 和 dataType , contentType 主要设置你发送给服务器的格式,dataType设置你收到服务器数据的格式。
在http 请求中,get 和 post 是最常用的。在 jquery 的 ajax 中, contentType都是默认的值:application/x-www-form-urlencoded,这种格式的特点就是,name/value 成为一组,每组之间用 & 联接,而 name与value 则是使用 = 连接

traditional
在使用ajax向后台传值的时候,有的时候一个字段需要传多个值,这种情况下会想到用数组形式来传,比如:
data: {
    "records": ["123","456","789"]
  },

  

 
      $.ajax({ 
                url: url,
                type: 'POST',
                //traditional: true,// 
                dataType: "json", 
                data: data,
                success: function(result, textStatus, xhr) {
                    console.log(result, textStatus, xhr)
                },
                error: function(result, textStatus, xhr) {

                    console.log(result)

                },
                complete: function(result, textStatus) {
                    console.info(result.responseJSON, textStatus);
                }
            });

  

后端接收:

   ReqInfo reqInfo = Request.Model<ReqInfo>();

  

2.Ajax FormBody
  $.ajax({
                
                url: url,
                type: 'POST',
                traditional: true, 
                contentType: "application/json",
                dataType: "json",
                data: JSON.stringify(data), 
                success: function(result, textStatus, xhr) {
                    console.log(result, textStatus, xhr)
                },
                error: function(result, textStatus, xhr) {

                    console.log(result)

                },
                complete: function(result, textStatus) {
                    console.info(result.responseJSON, textStatus);
                }
            });

后端接收:

   ReqInfo reqInfo = Request.Model<ReqInfo>();

 

netcore3.后台接收数据:

  #region 
        /// <summary>
        /// 
        /// </summary> 
        /// <returns></returns>
        [HttpPost] 
        public async Task<IActionResult> Synaddress()
        {
            AddressResult Res = null; 
            try
            {
                model = Request.Model<addRequest>();
              
            }
            catch (Exception e)
            {
                 
            }
            return new JsonResult(Res);
        }
        #endregion

  

 model = Request.Model<RequestMode>();

RequestExtensions

 

using System;
using System.IO; 
using System.Text; 
using System.Reflection; 
using Microsoft.AspNetCore.Http;
using System.Text.Json;
using Microsoft.AspNetCore.Http.Internal;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;

namespace System.Extensions
{
    public static class RequestExtensions
    { 

        #region GET请求获得对象[HttpGet]
        /// <summary>
        /// GET请求获取参数
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static T QueryModel<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.Query[property.Name].Count > 0)
                    {
                        property.SetValue(t, Convert.ChangeType((object)request.Query[property.Name][0], ConversionType.InitConversionType(property)), null);
                    }
                }
            }
            catch (Exception e)
            {
                throw e;
            }

            return t;
        }
        #endregion


        #region HttpPost
        #region Form请求获得对象[HttpPost]
        /// <summary>
        ///  Form请求获得对象
        ///  每种类型必须是常用类型
        /// </summary>
        /// <param name="request"></param>
        /// <returns> </returns>
        public static T FormModel<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)
                    {
                        if (!string.IsNullOrEmpty(request.Form[property.Name][0]))
                        {
                            property.SetValue(t, Convert.ChangeType((object)request.Form[property.Name][0], ConversionType.InitConversionType(property)), null);
                        } 
                    }
                }
            }
            catch (Exception)
            {
                t = default;
            }
            return t;
        }
        #endregion

        #region Body请求获得字符串[HttpPost]
        /// <summary>
        /// GetBody
        /// </summary>
        /// <param name="Request"></param>
        /// <returns></returns>
        public static string Bodys(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;
        }
        #endregion

        #region Body异步请求获得字符串[HttpPost]
        /// <summary>
        /// Body异步请求获得字符串[HttpPost]
        /// </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 Body请求获得对象[HttpPost]
        /// <summary>
        /// Body请求获得对象
        /// </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;
        }
        #endregion

        #region Body异步请求获得对象[HttpPost]
        /// <summary>
        /// Body异步请求获得对象
        /// </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>(json:body, JsonOpt.UnicodeRangesAll);
                    t = Newtonsoft.Json.JsonConvert.DeserializeObject<T>(body);
                }
            }
            catch (Exception e)
            { 
                throw e;
            }
            return t;
        }
        #endregion
        #endregion


        #region 获取请求参数[对象]
        /// <summary>
        /// 适用于HttpGet/HttpPost请求
        /// 对于其他请求后期待完善
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="request"></param>
        /// <returns></returns>
        public static T Model<T>(this HttpRequest request)
            where T : class, new()
        {
            T t = new T();
            try
            {
                if (request.Method.ToUpper().Equals("GET")) t = request.QueryModel<T>();
                else if (request.HasFormContentType) t = request.FormModel<T>();
                else t = request.BodyModelAsync<T>().GetAwaiter().GetResult();
            }
            catch (Exception e)
            { 
                throw e;
            }
            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 BodyModels<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 获得客户端真实IP地址
        /// <summary>
        /// 获得客户端真实IP地址
        /// </summary>
        /// <param name="request"></param>
        /// <returns>IP地址</returns>
        public static string GetUserRealIp(this HttpRequest request)
        {
            string proxyIps = request.Headers["X-Forwarded-For"];
            if (!string.IsNullOrWhiteSpace(proxyIps))
                return proxyIps.Split(',')[0].Trim();

            //return request.UserHostAddress;
            string ip = string.Empty;
            if (request != null)
            {
                ip = request.Headers["X-Real-IP"].ToString();
                if (request.Headers.ContainsKey("X-Real-IP") && !string.IsNullOrEmpty(ip))
                {
                    return ip;
                }

                ip = request.Headers["X-Forwarded-For"].ToString();
                if (request.Headers.ContainsKey("X-Forwarded-For") && !string.IsNullOrEmpty(ip))
                {
                    return ip;
                }
            }

            if (request.HttpContext.Connection != null)
            {
                if (request.HttpContext.Connection.RemoteIpAddress != null)
                {
                    ip = request.HttpContext.Connection.RemoteIpAddress.ToString();
                }
            }
            if (!ip.IsEmpty()) ip = ip.Substring(ip.LastIndexOf(':') + 1);
            return ip;
        }
        #endregion

    }
}

  


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM