fluffybonkers fluffybonkers - 24 days ago 7x
JSON Question

Empty JSON Response from Controller in C# Web API

I am learning about building web APIs in C#.

I am testing my controller, however I am getting an empty


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
. 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();

public void getClassListByTermTest()
List<string> output = testRepo.getClassListByTerm("316a");
foreach (string className in output)

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 the 316a - I thought they were just like the parentheses used in a method signature for receiving a parameter, but I presume they are used for passing list/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 string 316a gets passed to the query.

Thank you all.