Brian Baldner
Brian Baldner

Reputation: 51

Why am I getting this error while making a asp.net web api?

Controller.cs

[HttpGet]
    public async Task<ActionResult<IEnumerable<RankDistribution>>> GetTodoItems()
    {
        List<rank> rklist = new List<rank>();
        rank rk = new rank
        {
            rankID = 0,
            rankName = "Plastic 1",
            playersInRank = 1,
            percentInRank = 100f
        };
        rklist.Add(rk);
        var rb = new RankDistribution
        {
            Id = 0,
            rank = rklist
        };
        return rb;
    }

Class.cs

public class RankDistribution
{
    public long Id { get; set; }
    public List<rank> rank { get; set; }
}
public class rank
{
    public string rankName { get; set; }
    public int rankID { get; set; }
    public int playersInRank { get; set; }
    public float percentInRank { get; set; }
}

Error Message

Cannot implicitly convert type 'RankAPI.Models.RankDistribution' to 'Microsoft.AspNetCore.Mvc.ActionResult<System.Collections.Generic.IEnumerable<RankAPI.Models.RankDistribution>>

I have only recently started working on an api, but I am pretty familiar on C#. How do I convert the return value so it goes through? Thanks!

Upvotes: 1

Views: 87

Answers (1)

Zinov
Zinov

Reputation: 4119

You are returning a single item of RankDistribution

You should include it in a List and return the list

var toRet = new List<RankDistribution>();
toRet.Add(rb);
return toRet;

But in my opinion if you have the RankDistribution that contains a list inside of the items you want to return why not returning just rb and change the syntax of your method to

ActionResult<RankDistribution>

Upvotes: 2

Related Questions