Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Core Error: The JSON value could not be converted to System.String [duplicate]

I am trying to perform a search functionality in ASP.NET Core. This is my controller:

[HttpPost("searchbyname")]
   public async Task<ActionResult<List<SelectedChildDto>>> SearchByName([FromBody]string firstName)
   { if (string.IsNullOrWhiteSpace(firstName)) { return new List<SelectedChildDto>(); }
            return await _context.Children
                .Where(x => x.FirstName.Contains(firstName))
                .OrderBy(x => x.FirstName)
                .Select(x => new SelectedChildDto { Cld = x.Cld, ChildCode = x.ChildCode, 
                 FirstName = x.FirstName, PhotoPath = x.PhotoPath })
                .Take(5)
               .ToListAsync();               
              
        }

I have this DTO class from the model

namespace API.Dtos
{
    public class SelectedChildDto
    {
      
        public int Cld { get; set; }

        public string ChildCode { get; set; }
     
        public string FirstName { get; set; }
         public string PhotoPath { get; set; }
    }
}

This is my error output:

"errors": {
        "$": [
            "The JSON value could not be converted to System.String. Path: $ | LineNumber: 0 | BytePositionInLine: 1."
        ]
    }

How can I fix this?

like image 467
King Genius Avatar asked Nov 02 '25 11:11

King Genius


1 Answers

The problem is related to System.Text.Json deserialization of body text for the single [FromBody] string firstName argument of your controller. For example, you need just to send "John" in body instead of full-featured JSON {"firstName": "John"}.

Check also this answer to the similar question.

like image 119
Vlad Rudenko Avatar answered Nov 04 '25 00:11

Vlad Rudenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!