记录 POST 请求正文中的模型数据
我的要求是记录我从 POST 请求接收到的模型数据。但是当我尝试从 ModelState.Values 获取值时,我没有收到任何内容。我也尝试记录请求正文,但与请求正文相同,我没有收到任何数据。
[Route("")]
[HttpPost]
public IActionResult Send([FromBody]RequestDto model)
{
return CreateResponse(() => _sendTask.Send(model, false));
}
[ApiController]
public class ApiController : ControllerBase
{
#region Protected methods
protected IActionResult CreateResponse()
{
try
{
if (ModelState.IsValid)
{
StringBuilder value = new StringBuilder();
foreach (ModelStateEntry values in ModelState.Values)
{
value.Append(values);
}
return BadRequest(value.ToString());
}
catch (Exception ex)
{
Logger.LogCritical("Exception occurred during processing of a request", ex);
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
My requirement is to log the model data that I am receiving from a POST request. but when I am tring to get the values from ModelState.Values, I am not receiving anything. I also tried to Log Request body, but same with the request body also, I am not receiving any data.
[Route("")]
[HttpPost]
public IActionResult Send([FromBody]RequestDto model)
{
return CreateResponse(() => _sendTask.Send(model, false));
}
[ApiController]
public class ApiController : ControllerBase
{
#region Protected methods
protected IActionResult CreateResponse()
{
try
{
if (ModelState.IsValid)
{
StringBuilder value = new StringBuilder();
foreach (ModelStateEntry values in ModelState.Values)
{
value.Append(values);
}
return BadRequest(value.ToString());
}
catch (Exception ex)
{
Logger.LogCritical("Exception occurred during processing of a request", ex);
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当我们收到请求正文中包含数据的 post 请求时,我认为我们无法从
ModelState.Values
获取值,您可能会看到下面的屏幕截图,ModelState.Values
> 不包含数据,我们需要从模型本身获取数据。另一个例子,请看我下面的屏幕截图,当我向我的api发送这样的post请求时,我可以在我的模型中看到数据,但在请求正文或modelstate.value中没有数据
When we received a post request which contained data in request body, I don't think we can get the value from
ModelState.Values
, you may see screenshot below,ModelState.Values
doesn't contain data, we need to get data from the Model itself.Another example, see my following screenshot, when I send such post request to my api, I can see data in my model but no data in request body or modelstate.value