gpt4 book ai didi

c# - ASP.NET Core 6 - 如何在不反序列化的情况下通过 MapPost() 获取 JSON 输入?

转载 作者:行者123 更新时间:2023-12-05 04:38:49 25 4
gpt4 key购买 nike

我是 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\"}"

enter image description here


更新:

原始请求的正确解决方案:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com