英文:
How to return a dynamic object list from web api in c#
问题
I Have an object
public class GeneralResponseClass
{
public int ErrorCode { set; get; }
public string Date { set; get; }
public String ErrorMessage { set; get; }
public List<dynamic> Data = new List<dynamic>();
public bool Success { set; get; }
public GeneralResponseClass()
{
Date = DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss");
}
}
in my API Function i want to return the object
[HttpGet]
public GeneralResponseClass Get()
{
GeneralResponseClass generalResponseClass = new GeneralResponseClass();
generalResponseClass.ErrorCode = 0;
generalResponseClass.ErrorMessage = "";
generalResponseClass.Success = false;
generalResponseClass.Data.Add(new
{
Name = "User 1",
Email = "User1@user.com"
});
generalResponseClass.Data.Add(new
{
Name = "User 2",
Email = "User2@user.com"
});
return generalResponseClass;
}
in the response i get don't get the List
{
"errorCode": 0,
"date": "06/01/2020 16:32:12",
"errorMessage": "",
"success": false
}
Why doesn't the List<dynamic> Data
return?
英文:
I Have an object
public class GeneralResponseClass
{
public int ErrorCode { set; get; }
public string Date { set; get; }
public String ErrorMessage { set; get; }
public List<dynamic> Data = new List<dynamic>();
public bool Success { set; get; }
public GeneralResponseClass()
{
Date = DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss");
}
}
in my API Function i want to return the object
[HttpGet]
public GeneralResponseClass Get()
{
GeneralResponseClass generalResponseClass = new GeneralResponseClass();
generalResponseClass.ErrorCode = 0;
generalResponseClass.ErrorMessage = "";
generalResponseClass.Success = false;
generalResponseClass.Data.Add(new
{
Name = "User 1",
Email = "User1@user.com"
});
generalResponseClass.Data.Add(new
{
Name = "User 2",
Email = "User2@user.com"
});
return generalResponseClass;
}
in the response i get don't get the List
{
errorCode: 0,
date: "06/01/2020 16:32:12",
errorMessage: "",
success: false
}
Why The List<dynamic> Data dont return?
答案1
得分: 2
你不能返回带有“anonymous”对象的集合。您可以使用类似于“anonymous”的“ExpandoObject”。您还可以为您的对象类型创建一个自定义类,因为它们在您的情况下具有相同的属性(至少在模板中是这样的)。
您可以在这里查看更多关于“ExpandoObject”的信息:https://stackoverflow.com/questions/1653046/what-are-the-true-benefits-of-expandoobject
英文:
You cannot return any collection with anonymous
object. You can use ExpandoObject
which is simillar to anonymous
. You can also create a custom class for your type of object since they have the same properties in your case (at least in the template).
You can check for more on ExpandoObject
here: https://stackoverflow.com/questions/1653046/what-are-the-true-benefits-of-expandoobject
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论