0

I am trying to make Blazor APP that returns Employees list but when trying to return the list using GetJsonAsync the following error appears ....

JsonException: '<' is an invalid start of a value. Path: $ | LineNumber: 1 | BytePositionInLine: 0.

Controller Files:

[ApiController]
[Route("[controller]")]
public class EmployeesController : ControllerBase
{
    private readonly IEmployeeRepository employeeRepository;
    

    public EmployeesController(IEmployeeRepository employeeRepository)
    {
        this.employeeRepository = employeeRepository;
    }

    [HttpGet]
    public async Task<ActionResult> GetEmployees()
    {

        try
        {
            return Ok(await employeeRepository.GetEmployees());
        }
        catch (Exception)
        {
            return StatusCode(StatusCodes.Status500InternalServerError
                   ,"Error retrieving data from the database");
            
        }

    }

Services Class:

    public async Task<IEnumerable<Employee>> GetEmployees()
    {
        return await httpClient.GetJsonAsync<Employee[]>("employees");
    }

Blazor Base Class:

 public class EmployeeListBase : ComponentBase
{

    [Inject]
    IEmployeeService EmployeeService { get; set; }

    

    public IEnumerable<Employee> Employees { get; set; }

    protected override async Task OnInitializedAsync()
    {
        Employees = (await EmployeeService.GetEmployees()).ToList();
    }


}
Omar Sawy
  • 23
  • 1
  • 4
  • 1
    `return await httpClient.GetJsonAsync("employees");` "employees" is a very strange Uri. Have you set `HttpClient` `BaseAddress` ? It looks `GetJsonAsync` call receives HTML page. Like 404 status page – Roman Kalinchuk Jul 05 '20 at 06:51
  • i did in the configure services ` services.AddHttpClient(client => { client.BaseAddress = new Uri("https://localhost:44379/"); });` – Omar Sawy Jul 05 '20 at 07:27
  • 1
    Make sure you include the http or https in the BaseAddress Uri. Also have you verified your endpoint gets hit (by placing a breakpoint in the EmployeesController.GetEmployees method? – pinkfloydx33 Jul 05 '20 at 10:29
  • 1
    @RomanKalinchuk "employees" is perfectly valid. OP has set the base address and their controller route does not include 'api/'. So the correct route to request is "employees" however I think they need to fix the base address (which btw, [also has some oddities](https://stackoverflow.com/a/23438417/491907) – pinkfloydx33 Jul 05 '20 at 10:30
  • 2
    That error usually means there was HTML returned, not json. It is probably a 500, 404, etc., view which cannot be parsed as json. – Crowcoder Jul 05 '20 at 10:37
  • 1
    Thank you all for help ... after reading the oddities i fixed the URI and it worked .. You must place a slash at the end of the BaseAddress, and you must not place a slash at the beginning of your relative URI – Omar Sawy Jul 05 '20 at 12:45

0 Answers0