-1

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);
        }

1 Answers1

-1

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.

enter image description here enter image description here

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

[HttpPost]
public void getModel([FromBody] Movie model) {
    var request = HttpContext.Request.Body;
    if (ModelState.IsValid){
         var value = ModelState.Values;
    }
    var a = model.Price;
}

enter image description here

Tiny Wang
  • 10,423
  • 1
  • 11
  • 29
  • Hi, How can I get RequestDto model data and use it inside my APIController and log the data there. APIController is a base controller and all the other controllers are inherting from it. I want to Log all my model data there. – Sonal Khatri Mar 09 '22 at 08:35
  • You can't get the data in your `RequestDto` ? Any error messages? And how you send your request? I think you may refer to my code sample and do a simple test.... – Tiny Wang Mar 09 '22 at 09:22