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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With