dolly_do
dolly_do

Reputation: 127

Error CS0029 Cannot implicitly convert type 'Microsoft.AspNetCore.Mvc.ActionResult' to 'System.Collections.Generic.List<>'

I tried the solutions posted on StackOverflow, but none of them worked. I have a method calling a web service. The code is as following and I keep getting a compiler error:

    public async Task<ActionResult <List<items>>>getitems()
    {
        HttpClient client = new HttpClient();
        client.BaseAddress = new Uri("https://localhost:5001/");
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(
        new MediaTypeWithQualityHeaderValue("application/json"));
        var Res = await client.PostAsJsonAsync("api/sub", ids);
        Res.EnsureSuccessStatusCode();
        if (Res.IsSuccessStatusCode)
        {
            var Response = Res.Content.ReadAsStringAsync().Result;   
            var sub = JsonConvert.DeserializeObject<JArray>(Response);
            List<items> item = sub.ToObject<List<items>>();
            return Ok(item);
        }
    }

Then I call the method from a different class as following:

    public async Task<List<items>> getService(List<string> ids)
    {
        var IdentificationIdsToOrder = new JObject();
        foreach (var id in ids)
        {
            var newId = new JProperty("ids", id);
            IdentificationIdsToOrder.Add(newId);
        }
        _controller = new getitems();
        var Res = await _controller.getitems();         
        var ItemList = Res.Result;
        return ItemList;
    }
}

Here it goes wrong with the return value and I can't compile.

What I'm missing?

Upvotes: 0

Views: 12141

Answers (1)

Fyodor Yemelyanenko
Fyodor Yemelyanenko

Reputation: 11848

In getService method you should use var ItemList = Res.Value; in place of var ItemList = Res.Result;

public async Task<List<items>> getService(List<string> ids)
{
    var IdentificationIdsToOrder = new JObject();
    foreach (var id in ids)
    {
        var newId = new JProperty("ids", id);
        IdentificationIdsToOrder.Add(newId);
    }

    _controller = new getitems();
    var Res = await _controller.getitems();         
    var ItemList = Res.Value;
    return ItemList;

}

Upvotes: 1

Related Questions