Giorgi Krialashvili
Giorgi Krialashvili

Reputation: 25

Return the List items from C# MVC Controller

So I have this code and it should return the list of items but I can't get it to work. I know there is a mismatch between HttpResponseMessage and List<string> but I am not able to convert it to return.

image

I know that it's because of the HttpResponseMessage type and list don't match but I don't know how to convert it

namespace NovaWebApi.Controllers
{
    public class TermsController : WebApiBase
    {
        [HttpGet]
        public HttpResponseMessage GetTermsUrl()
        {
            List<string> terms = new List<string>();
            terms.Add("https://www.nbg.gov.ge/index.php?m=2");
            terms.Add("https://www.fms.gov.ge/");

            return terms;
        }
    }

}

Upvotes: 1

Views: 8207

Answers (3)

Mark Schultheiss
Mark Schultheiss

Reputation: 34168

Since you indicate you wish to return HttpResponseMessage type, you have to create one that includes your list.

Web API will create a serialized version in the response body using a formatter for the model, in this case your list; writing the serialized model into the response body.

[HttpGet]
public HttpResponseMessage GetTermsUrl()
{
     // Get a list of products from a database.
     List<string> terms = new List<string>();
     terms.Add("https://www.nbg.gov.ge/index.php?m=2");
     terms.Add("https://www.fms.gov.ge/");
     // Write the list to the response body.
     HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, terms);
     return response;
)

Upvotes: 1

MrElectrQ
MrElectrQ

Reputation: 52

Your HttpGet method returns HttpResponseMessage.Try this one:

[HttpGet]

    public List<string> GetTermsUrl()
    {
        List<string> terms = new List<string>();
        terms.Add("https://www.nbg.gov.ge/index.php?m=2");
        terms.Add("https://www.fms.gov.ge/");

        return terms;
    }

Upvotes: 2

You are trying to return List<string> as HttpResponseMessage which is not possible.Try this:

public class TermsController : Controller // this part to return Ok() without error.

Then:

return Ok(terms);

Upvotes: 1

Related Questions