简体   繁体   中英

Blazor Server Project

I'm new to C#. Was trying to call a rest api in a Blazor server project and I got this error: JsonException: '<' is an invalid start of a value. Path: $ | LineNumber: 1 | BytePositionInLine: 0.

My Service:

    public class EmployeeService : IEmployeeService
    {
        private readonly HttpClient httpClient;

        public EmployeeService(HttpClient httpClient)
        {
            this.httpClient = httpClient;
        }
        public async Task<IEnumerable<Employee>> GetEmployees()
        {
             return await httpClient.GetJsonAsync<Employee[]>("api/employees");
           
        }
    }

My controller:

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

        //EmployeeRepository objemployee = new 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 DB");
            }
      }
}

Try something like this in your EmployeeService , it will help towards knowing what went wrong when debugging. You can inspect the response.ReasonPhrase to start off with.

public async Task<IEnumerable<Employee>> GetEmployees()
    {

        var response = await httpClient.GetAsync("api/employees");
        if (response.IsSuccessStatusCode)
        {
            var result = await JsonSerializer.DeserializeAsync<Employee[]>(await response.Content.ReadAsStreamAsync(), new JsonSerializerOptions() { PropertyNameCaseInsensitive = true });
            return result;
        }
        else
        {
            //handle the response that was not successful here.
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM