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

相关推荐
刘梦凡呀3 天前
C# .NET Core 批量下载文件
windows·c#·.netcore
Zhen (Evan) Wang3 天前
.NET 6 WPF 利用CefSharp.Wpf.NETCore显示PDF文件
.net·wpf·.netcore
时光追逐者3 天前
C#/.NET/.NET Core拾遗补漏合集(25年4月更新)
c#·.net·.netcore
追雨潮3 天前
.net core 项目快速接入Coze智能体-开箱即用-第2节
.netcore
追雨潮4 天前
.net core 项目快速接入Coze智能体-开箱即用-全局说明
.netcore·ai编程
时光追逐者5 天前
C#/.NET/.NET Core技术前沿周刊 | 第 35 期(2025年4.14-4.20)
c#·.net·.netcore
全栈小55 天前
【C#】.net core 6.0调用MVC API接口时,提示Unsupported Media Type,状态码415
c#·mvc·.netcore
猫霸5 天前
理解.NET Core中的配置Configuration
html·.netcore·xhtml
MoFe15 天前
【.net core】【watercloud】数据库连接报错问题
数据库·.netcore
csdn_aspnet5 天前
Windows .NET Core 应用程序部署到 IIS 解决首次访问加载慢的问题
iis·.netcore