Home > Mobile >  How to Consume an API in ASP.NET Core?
How to Consume an API in ASP.NET Core?

Time:06-08

I need to consume an API in my MVC project. the actions in API are secured, So you need to access a token (JWT) to consume it. I face an error every time I try to deserialize the response into the model (Player). It says *Could not cast or convert from System.String to MyMVC.Models.Player* When I run a debugger, the piece of code including deserialization is in red in the internal server error page. Here is the action in API

        [HttpGet]
        [Authorize]
        public ActionResult<List<Player>> GetAllPlayers()
        {
            var players = _applicationDbContext.Players.OrderBy(p => p.Name).Select(p=> p.Name).ToList();
            return Ok(players);
        }

This is the action in the MVC project

public async Task<IActionResult> GetPlayers()
        {
            var token = HttpContext.Session.GetString("Token");
            List<Player> players = new List<Player>();
            var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost:53217/api/player");
            var client = _clientFactory.CreateClient();
            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
            HttpResponseMessage response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
            if(response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                var strResponse = await response.Content.ReadAsStringAsync();
                players = JsonConvert.DeserializeObject<List<Player>>(strResponse);

            }
            return View(players);

        }

CodePudding user response:

Sami Kuhmonen 's comment is right.

 var players = _applicationDbContext.Players.OrderBy(p => p.Name).Select(p=> p.Name).ToList();

From here we can get name list not player list.

Name list contain string name. Player list contain object player1 {name="xx",age="xx"}

But

List<Player> players = new List<Player>();
var strResponse = await response.Content.ReadAsStringAsync();
players = JsonConvert.DeserializeObject<List<Player>>(strResponse); 

here we need player list contain object players .

You can use below code in your API to get the playerlist.

var players = _applicationDbContext.Players.ToList();

enter image description here

I reproduce your problem. Then I use that method to solve it.

enter image description here

  • Related