我是 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;
});
cURL API 測驗示例:
curl -X POST 'https://localhost:5001/add_data/my_first_entry' -d '{"name":"Sebastian", "age":35, "car":"Renault"}' -H 'Content-Type :應用程式/json'
預期回應:
'{"name":"Sebastian", "age":35, "car":"Renault"}'
是否可以?
uj5u.com熱心網友回復:
只需將 [FromBody] 屬性添加到 body 中,它就會按預期作業。
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;
}
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/396432.html
