Issue
I just started learning web API using ASP.NET. I created a new project from visual studio and trying to understand MVC folder structure and API calls.
Here what I want to know is: why do we need IEnumerable<string>
before the get
method.
In myValuesController.cs
,
// GET api/values
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
According to the Microsoft Documentation, this exposes the enumerator, which supports a simple iteration over a collection of a specified type but think if I have an integer in my database do I need to convert it into string as well?
Solution
IEnumerable<string>
is a return type of Get()
action method. If your api is returning any value then you need to give that type as a return type of a function
If I have an integer in my database do I need to convert it into
string as well?
- No, then you can return given integer and return type of that api endpoint will be
int
,
like,
//+ Access Modifier
//| + Return Type
//| | + Function name
public int Get()
{
return 200; //status code for Ok.
}
Regarding IEnumerable<>
:
If you have multiple integers and want to return collection of these integers, then use IEnumerable<int>
From MSDN documentation IEnumerable Interface
:
Exposes an enumerator, which supports a simple iteration over a
non-generic collection.
Answered By – Prasad Telkikar
Answer Checked By – Marie Seifert (BugsFixing Admin)