一、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 } }