Logging the model data from the POST request body

sonal khatri 81 Reputation points
2022-03-09T03:38:38.317+00:00

Hi,

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);
    }
Developer technologies | ASP.NET | ASP.NET Core
{count} votes

6 answers

Sort by: Most helpful
  1. Anonymous
    2022-03-09T08:38:18.72+00:00

    Hi anonymous user,

        if (ModelState.IsValid)    
    
         {  
            StringBuilder value = new StringBuilder();  
            foreach (ModelStateEntry values in ModelState.Values)  
            {  
               value.Append(values);  
            }  
            return BadRequest(value.ToString());  
         }  
    

    Model state represents errors that come from two subsystems: model binding and model validation. Errors that originate from model binding are generally data conversion errors. For example, an "x" is entered in an integer field. Model validation occurs after model binding and reports errors where data doesn't conform to business rules. For example, a 0 is entered in a field that expects a rating between 1 and 5.

    The ModelState.Values stores the invalid model property and its Model validation error message.

    If the model validation is valid (ModelState.IsValid is true), the ModelState.Values is empty, if the ModelState.IsValid is false, the ModelState.Values contains the invalid property and the error message, check this screenshot:

    181375-2.gif

    So, if you want to get ModelState.Values, try to modify your code as below:

        [HttpPost("send")]  
        public IActionResult Post([FromBody] RequestDto dto)  
        {  
            if (ModelState.IsValid)  
            {  
                //model id valid.  
            }  
            else  
            {   
                //model is invalid  
                StringBuilder value = new StringBuilder();  
                foreach (ModelStateEntry values in ModelState.Values)  
                {  
                    value.Append(values);  
                }  
            }  
            return Ok(dto);  
        }  
    

    [Note] In the above sample, it is not an API method. Web API controllers don't have to check ModelState.IsValid if they have the [ApiController] attribute. In that case, an automatic HTTP 400 response containing error details is returned when model state is invalid. For more information, see Automatic HTTP 400 responses and Model validation in ASP.NET Core MVC and Razor Pages.

    return CreateResponse(() => _sendTask.Send(model, false));

    Besides, it seems that you want to transfer the model to the CreateResponse method, if that is the case, you can add a parameter in the CreateResponse method to receive the model, like this:

        [HttpPost("send")]  
        public IActionResult Post([FromBody] RequestDto dto)  
        {  
            if (ModelState.IsValid)  
            {  
                //model id valid.  
                CreateResponse(dto);  
            }  
            else  
            {   
                //model is invalid  
                StringBuilder value = new StringBuilder();  
                foreach (ModelStateEntry values in ModelState.Values)  
                {  
                    value.Append(values);  
                }  
            }  
            return Ok(dto);  
        }  
    
    
        protected void CreateResponse(RequestDto model)  
        {  
            var name = model.Name;  
        }  
    

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Dillion

    0 comments No comments

  2. sonal khatri 81 Reputation points
    2022-03-09T08:56:03.18+00:00

    Hi , I am sending the post request with some body.

    And I am getting the Model errors as "The json couldn't be converted to RequestDto. The ModelState is valid and I am not getting any values in ModelState.Values as you have explained.

    But I want to log what is inside the body of the post request so that I can resolve the issue.
    How can I log the RequestDto model data?

    Thanks


  3. sonal khatri 81 Reputation points
    2022-03-09T09:15:27.89+00:00
    public class RequestDto
        {
    
            public int TypeId { get; set; }
    
    
            public string RecipientEmailAddress { get; set; }
    
    
            public string Body { get; set; }
        }
    

    Request Body:
    {
    typeId : "1",
    recipientEmailAddress : "some email address",
    body : "Hi"

    }

    0 comments No comments

  4. sonal khatri 81 Reputation points
    2022-03-09T09:24:30.87+00:00
    [ApiController]
    [Route("")]
     public class MailController : BaseApiController
    {
            [Route("send")]
            [HttpPost]
            [UserPermission(UserPermissionEnum.EmailSettings)]
            public IActionResult Send([FromBody]RequestDto model)
            {
                return CreateResponseMessage(() => _mailTask.Send(model, false));
            }
    }
    [ApiController]
     public class BaseApiController : ControllerBase
     {
            #region Protected methods
    
          protected IActionResult CreateResponseMessage(Func<ValidationResult> someMethod)
          {
    
                try
                {
                        if (someMethod == null)
                             throw new ArgumentNullException(nameof(someMethod));
    
                        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);
            }
    

    I want to log the model data in my BaseAPIController for where controller action.

    0 comments No comments

  5. Anonymous
    2022-03-09T09:36:10.807+00:00

    Hi anonymous user,

    Request Body:
    {
    typeId : "1",
    recipientEmailAddress : "some email address",
    body : "Hi"

    }

    The request body is an invalid Json format, so it can't used to bind the model and the model parameter is null.

    By using the above invalid Json string, the result like this:

    181279-1.gif

    Model state represents errors that come from two subsystems: model binding and model validation. Errors that originate from model binding are generally data conversion errors. For example, an "x" is entered in an integer field. Model validation occurs after model binding and reports errors where data doesn't conform to business rules. For example, a 0 is entered in a field that expects a rating between 1 and 5.

    So, from the above screenshot, we can see it will show the model binding error.

    Try to change the request body as below (use a valid Json string):

    {  
       "typeId":"1",  
       "recipientEmailAddress":"some email address",  
       "body":"Hi"  
    }  
    

    Then the result as below:

    181401-2.gif


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Dillion

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.