use*_*673 5 c# rest json curl asp.net-core
我对 C#、JSON 和 Web 编程总体来说是新手,所以如果我对某些概念有误解的迹象,请纠正我。
在 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;
});
Run Code Online (Sandbox Code Playgroud)
cURL API 测试的示例:
curl -X POST 'https://localhost:5001/add_data/my_first_entry' -d '{"name":"Sebastian", "age":35, "car":"Renault"}' -H 'Content-Type :应用程序/json'
预期回应:
'{“姓名”:“塞巴斯蒂安”,“年龄”:35,“汽车”:“雷诺”}'
是否可以?
只需将 [FromBody] 属性添加到 body 中,它就会按预期工作。
app.MapPost("/add_data/{queryKey}", (string queryKey, [FromBody] string jsonstring) =>
{
mydictionary.Add(queryKey, jsonstring);
return jsonstring;
});
Run Code Online (Sandbox Code Playgroud)
要求:
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\"}"
Run Code Online (Sandbox Code Playgroud)
更新:
原始请求的正确解决方案:
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;
}
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
12001 次 |
最近记录: |