作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我是 C#、JSON 和网络编程的新手,所以如果我对某些概念有误解,请指正。
在 ASP.NET Core 6 上,我想使用 MapPost() 获取 JSON 字符串,而不必反序列化它。我以前做过一个类并成功反序列化输入,但现在我想尝试纯字符串。这是我的 Web API 的一部分 Program.cs
的样子:
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
Dictionary<string, string> mydictionary = new();
app.MapPost("/add_data/{queryKey}", (string queryKey, string jsonstring) =>
{
mydictionary.Add(queryKey, jsonstring);
return jsonstring;
});
cURL API 测试示例:
curl -X POST 'https://localhost:5001/add_data/my_first_entry' -d'{"name":"Sebastian", "age":35, "car":"Renault"}' -H'Content-Type: application/json'
预期响应:
'{"name":"Sebastian", "age":35, "car":"Renault"}'
这可能吗?
最佳答案
只需将 [FromBody] 属性添加到主体,它就会按预期工作。
app.MapPost("/add_data/{queryKey}", (string queryKey, [FromBody] string jsonstring) =>
{
mydictionary.Add(queryKey, jsonstring);
return jsonstring;
});
要求:
POST /add_data/qq HTTP/1.1
Content-Type: application/json
User-Agent: PostmanRuntime/7.28.4
Accept: */*
Cache-Control: no-cache
Host: localhost:7297
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Content-Length: 21
"{ data = \"hello\"}"
更新:
原始请求的正确解决方案:
app.MapPost("/add_data/{queryKey}", async delegate(HttpContext context)
{
using (StreamReader reader = new StreamReader(context.Request.Body, Encoding.UTF8))
{
string queryKey = context.Request.RouteValues["queryKey"].ToString();
string jsonstring = await reader.ReadToEndAsync();
mydictionary.Add(queryKey, jsonstring);
return jsonstring;
}
});
关于c# - ASP.NET Core 6 - 如何在不反序列化的情况下通过 MapPost() 获取 JSON 输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70507720/
我是 C#、JSON 和网络编程的新手,所以如果我对某些概念有误解,请指正。 在 ASP.NET Core 6 上,我想使用 MapPost() 获取 JSON 字符串,而不必反序列化它。我以前做过一
我是一名优秀的程序员,十分优秀!