接收未知 JSON 到我的 API 并按下它
Recieving uknown JSON to my API and parsing it
我有 API,它从正文接收 JSON,它是从某些 WebUI 发送的。
[Route("api/[controller]")]
[ApiController]
public class MyController : ControllerBase
{
public IActionResult Create([FromBody] MyModel request)
{
MyModel newRecord = new();
try
{
newRecord.Id = null;
newRecord.Date = request.Date;
newRecord.Name = request.Name;
}
catch (Exception e)
{
return StatusCode(400, $"Error: {e.Message}");
}
return Ok(newRecord);
}
}
但是request
不是常数。它随着发展而变化。
正确知道我必须将 MyModel
与 request
匹配才能在 Body 中处理 JSON。但是它产生了太多的工作,因为有很多变化。
是否有解决方案,以便我可以接收未知的 JSON 对象并在控制器内部解析它?
比如有没有什么技巧,我可以这样写
public IActionResult Create([FromBody] var request)
或类似的东西?
System.Text.Json 有一个名为 JsonElement 的 class,可用于将任何 JSON 绑定到它。
[HttpPost]
public IActionResult Create([FromBody] JsonElement jsonElement)
{
// Get a property
var aJsonProperty = jsonElement.GetProperty("aJsonPropertyName").GetString();
// Deserialize it to a specific type
var specificType = jsonElement.Deserialize<SpecificType>();
return NoContent();
}
我有 API,它从正文接收 JSON,它是从某些 WebUI 发送的。
[Route("api/[controller]")]
[ApiController]
public class MyController : ControllerBase
{
public IActionResult Create([FromBody] MyModel request)
{
MyModel newRecord = new();
try
{
newRecord.Id = null;
newRecord.Date = request.Date;
newRecord.Name = request.Name;
}
catch (Exception e)
{
return StatusCode(400, $"Error: {e.Message}");
}
return Ok(newRecord);
}
}
但是request
不是常数。它随着发展而变化。
正确知道我必须将 MyModel
与 request
匹配才能在 Body 中处理 JSON。但是它产生了太多的工作,因为有很多变化。
是否有解决方案,以便我可以接收未知的 JSON 对象并在控制器内部解析它?
比如有没有什么技巧,我可以这样写
public IActionResult Create([FromBody] var request)
或类似的东西?
System.Text.Json 有一个名为 JsonElement 的 class,可用于将任何 JSON 绑定到它。
[HttpPost]
public IActionResult Create([FromBody] JsonElement jsonElement)
{
// Get a property
var aJsonProperty = jsonElement.GetProperty("aJsonPropertyName").GetString();
// Deserialize it to a specific type
var specificType = jsonElement.Deserialize<SpecificType>();
return NoContent();
}