I am learning about building web APIs in C#.
I am testing my controller, however I am getting an empty JSON
response.
This is my controller
public class ClassInfoController : ApiController
{
private ClassRepository classRepo = new ClassRepository();
public IList<string> getClassListByTerm(string termID)
{
List<string> classList = classRepo.getClassListByTerm(termID);
return classList;
}
This is my repository class which queries my Entity model
public class ClassRepository : IClass
{
private cet_databaseEntities db = new cet_databaseEntities();
public List<string> getClassListByTerm(string termID)
{
List<string> result = (from t in db.classCodeLookup
where t.termID == termID
orderby t.@class ascending
select t.@class).ToList<string>();
return result;
}
}
I have debugged my controller and when the API call is made, this repository class returns no data to the controller i.e. an empty list
. However, the reason I am confused, is that when I use the following test code on the repository class
public class ClassRepositoryTests
{
ClassRepository testRepo = new ClassRepository();
[TestMethod()]
public void getClassListByTermTest()
{
List<string> output = testRepo.getClassListByTerm("316a");
foreach (string className in output)
{
Console.WriteLine(className);
}
}
}
I get the result from the repository class I expect.
Why am I having this issue?
My issue was the automatic API documentation provided by a Web API project in Visual Studio told me that I should call my controller from the browser with the following:
http://localhost:51520/api/ClassInfo?termID={316a}
. Unbeknownst to me, this meant the{}
stayed with the316a
- I thought they were just like the parentheses used in a method signature for receiving a parameter, but I presume they are used for passinglist
/json
to a method (not relevant in this case). This meant that when my repository query ran, it returned nothing because I was not looking for the string{316a}
.If I call the API with the following address
http://localhost:51520/api/ClassInfo?termID=316a
it works because the string316a
gets passed to the query.Thank you all.
Try to add attribute to your API method
or you can use another class object for request data. I mean
I had a class inheriting from DynamicObject, and that would only return empty JSON (while XML seemed to return properly).
In my case, I was able to remove the DynamicObject inheritance and JSON serialization started working.
Unfortunately, I didn't have a chance to look into why
DynamicObject
breaks JSON serialization.