.net core 接口,动态接收各类型请求的参数

HttpPost

public async Task<IActionResult> testpost([FromForm] object info)

{
//Postman工具测试结果:
//FromBody,Postman的body只有=raw+json时才进的来
//参数为空时,Body(form-data、x-www-form-urlencoded)解析到的数据也有所不同

Dictionary<string,object> parmsVals=new Dictionary<string,object>();

try

{

if (HttpContext.Request.Body != null)

{

Stream _stream = HttpContext.Request.Body;

//_stream.Position = 0;

using (StreamReader reader = new StreamReader(_stream, Encoding.UTF8))

{

string strv = await reader.ReadToEndAsync();

if (!string.IsNullOrEmpty(strv) && strv.Trim().StartsWith("{") && strv.Trim().EndsWith("}"))

{

parmsVals = JsonConvert.DeserializeObject<Dictionary<string, object>>(strv.Trim());

}

else

{

parmsVals.Add("stream_str", strv);

}

}

}

}

catch { }

if (info != null && JsonConvert.SerializeObject(info).Trim()!="{}")

{

parmsVals.Add("info", JsonConvert.SerializeObject(info));

}

try

{

var files = Request.Form.Files;

if (files != null && files.Count > 0)

{

}

}

catch { }

if (HttpContext.Request.Query.Keys.ToList() != null)

{

List<string> lst = HttpContext.Request.Query.Keys.ToList();

foreach (string key in lst)

{

if (!parmsVals.ContainsKey(key))

{

parmsVals.Add(key, Request.Query[key].ToString().Trim());

}

}

}

try

{

if (HttpContext.Request.Form != null)

{

List<string> lst = HttpContext.Request.Form.Keys.ToList();

foreach (string key in lst)

{

if (!parmsVals.ContainsKey(key))

{

parmsVals.Add(key, Request.Form[key].ToString().Trim());

}

}

}

}

catch(Exception ex)

{

string msg = ex.Message;

}

//Values/testurl

return Content(JsonConvert.SerializeObject(parmsVals));

}

一、Body以 from-data 传参数

二、Body以 x-www-from-urledcoded 传参数

三、Body以 raw+JSON 传参数

相关推荐
武藤一雄2 天前
C# 异常(Exception)处理避坑指南
windows·microsoft·c#·.net·.netcore·鲁棒性
csdn_aspnet3 天前
在 ASP.NET Core 中使用自定义属性实现 HTTP 请求和响应加密
http·asp.net·.netcore
观无3 天前
.NET Core + Ocelot 网关 跨域 (CORS) 配置
状态模式·.netcore
csdn_aspnet3 天前
如何在 .NET Core WebAPI 和 Javascript 应用程序中安全地发送/接收密钥参数
javascript·.netcore·cryptojs
武藤一雄6 天前
C# 异步回调与等待机制
前端·microsoft·设计模式·微软·c#·.netcore
武藤一雄6 天前
C#万字详解 栈与托管堆 的底层逻辑
windows·microsoft·c#·.net·.netcore
武藤一雄6 天前
深入拆解.NET内存管理:从GC机制到高性能内存优化
windows·microsoft·c#·.net·wpf·.netcore·内存管理
武藤一雄8 天前
WPF/C# 应对消息洪峰与数据抖动的 8 种“抗压”策略
windows·微软·c#·wpf·.netcore·防抖·鲁棒性
武藤一雄9 天前
C# 竟态条件
microsoft·c#·.net·.netcore
武藤一雄9 天前
WPF深度解析Behavior
windows·c#·.net·wpf·.netcore