.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 传参数

相关推荐
[email protected]15 小时前
ASP.NET Core SignalR - 部分客户端消息发送
后端·asp.net·.netcore
bbsh209915 小时前
WebFuture:Ubuntu 系统上在线安装.NET Core 8 的步骤
linux·ubuntu·.netcore·webfuture
MoFe11 天前
【.net core】【watercloud】树形组件combotree导入及调用
.netcore
MoFe11 天前
【.net core】.KMZ文件解压为.KML文件并解析为GEOJSON坐标数据集。附KML处理多线(LineString)闭环问题
.netcore
The Future is mine2 天前
在.NET Core控制器中获取AJAX传递的Body参数
c#·.netcore
无味无感2 天前
ASP.NET Core使用Quartz部署到IIS资源自动被回收解决方案
.netcore
MoFe12 天前
【.net core】天地图坐标转换为高德地图坐标(WGS84 坐标转 GCJ02 坐标)
java·前端·.netcore
步、步、为营3 天前
.NET Core接口IServiceProvider
.net·.netcore
冰茶_5 天前
建造者模式:优雅构建复杂对象
设计模式·微软·c#·.netcore·建造者模式·软件开发
冰茶_6 天前
结构型设计模式之桥接模式
学习·设计模式·微软·c#·.netcore·桥接模式