如何将对象列表作为IHttpActionResult返回?

我是ASP.NET webapi的新手,我找不到返回id查询对象列表的方法。

这是GET请求的控制器方法。 我想返回所有通过url传递指定问卷的问题。

我试过这个:

// GET: api/Questions/5 [ResponseType(typeof(List))] public Task GetQuestion(int questionnaireId) { var questions = from q in db.Questions where q.QuestionnaireId == questionnaireId select new Question() { Id = q.Id, ImageLink = q.ImageLink, QuestionnaireId = q.QuestionnaireId, Text = q.Text }; return questions; } 

这是我的问题类:

 public class Question { public int Id { get; set; } [ForeignKey("Questionnaire")] public int QuestionnaireId { get; set; } public string Text { get; set; } public string ImageLink { get; set; } public virtual Questionnaire Questionnaire { get; set; } } 

但在return questions它显示编译器错误:

无法将类型System.Linq.IQueryable隐式转换为System.Web.Http.IHttpActionResult 。 存在显式转换(您是否错过了演员?)

我想得到一份问卷清单,这些问题是在问卷调查中查询的,这是通过url传递的,即api / questions / 2 ==>通过问卷调查表ID = 2给我回复所有问题。

您正在使用[ResponseType]属性,但这仅用于生成文档,请参阅MSDN:ResponseTypeAttribute类 :

当声明的返回类型为HttpResponseMessage或IHttpActionResult时,使用此选项指定操作返回的实体类型。 生成ApiDescription时,ApiExplorer将读取ResponseType。

您可以更改返回类型(并删除属性,因为不再需要该属性,因为将从实际签名生成返回类型文档):

 public IEnumerable GetQuestion(int questionnaireId) 

或者,如果您希望它是异步的:

 public async Task> GetQuestion(int questionnaireId) 

或者将结果包装在IHttpActionResultRequest.CreateResponse()执行此操作:

  return Request.CreateResponse>(HttpStatusCode.OK, questions); 

如果你调用ApiController.Ok()方法,后者就完成了:

 return Ok(questions); 

只需简单地返回它,你需要使用ApiController现在提供的一个很好的方法。

这将返回状态代码200以及您的问题集。

 [ResponseType(typeof(List))] public async Task GetQuestion(int questionnaireId) { var questions = from q in db.Questions where q.QuestionnaireId == questionnaireId select new Question() { Id = q.Id, ImageLink = q.ImageLink, QuestionnaireId = q.QuestionnaireId, Text = q.Text }; return this.Ok(questions); } 

首先,不要直接使用实体来提供数据。 为您的实体创建DTO:

 public class QuestionDto { public int id {get; set;} //put here getter and setter for all other Question attributes you want to have public QuestionDto(Question question){ this.id = question.id; ... and so on } } 

然后你的GET方法可能如下所示:

 // GET: api/Questions/5 public List GetQuestion(int questionnaireId) { IEnumerable questions = from q in db.Questions where q.QuestionnaireId == questionnaireId select new QuestionDto(q); return questions.toList(); } 

我还建议使用JSON进行数据传输,因为使用Javascript非常容易。

我认为你正在寻找类似于下面的代码:

 public IEnumerable Get(int id) { //Create the list that you need to return here // I am creating a new list and adding an object below just for // explaining the idea. var questions = new List(); questions.Add(new Question()); return questions; }