[英]How to return a list of objects as an IHttpActionResult?
我是ASP.NET webapi的新手,我找不到返回id查詢對象列表的方法。
這是我的GET請求的控制器方法。 我想返回所有通過網址傳遞指定問卷的問題。
我試過這個:
// GET: api/Questions/5
[ResponseType(typeof(List<Question>))]
public Task<IHttpActionResult> 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<finah_backend.Models.Question>
類型隱式轉換為System.Web.Http.IHttpActionResult
。 存在顯式轉換(您是否錯過了演員?)
我想得到一份問卷清單,這些問題是在問卷調查中查詢的,這是通過網址傳遞的,即api / questions / 2 ==>通過問卷調查表ID = 2給我回復所有問題。
您正在使用[ResponseType]
屬性,但這僅用於生成文檔,請參閱MSDN:ResponseTypeAttribute類 :
當聲明的返回類型為HttpResponseMessage或IHttpActionResult時,使用此選項指定操作返回的實體類型。 生成ApiDescription時,ApiExplorer將讀取ResponseType。
您可以更改返回類型(並刪除屬性,因為不再需要該屬性,因為將從實際簽名生成返回類型文檔):
public IEnumerable<Question> GetQuestion(int questionnaireId)
或者,如果您希望它是異步的:
public async Task<IEnumerable<Question>> GetQuestion(int questionnaireId)
或者將結果包裝在IHttpActionResult
, Request.CreateResponse<T>()
執行此操作:
return Request.CreateResponse<IEnumerable<Question>>(HttpStatusCode.OK, questions);
如果你調用ApiController.Ok()
方法,后者就完成了:
return Ok(questions);
只需簡單地返回它,你需要使用ApiController現在提供的一個很好的方法。
這將返回狀態代碼200以及您的問題集。
[ResponseType(typeof(List<Question>))]
public async Task<IHttpActionResult> 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<QuestionDto> GetQuestion(int questionnaireId)
{
IEnumerable<QuestionDto> questions = from q in db.Questions
where q.QuestionnaireId == questionnaireId
select new QuestionDto(q);
return questions.toList();
}
我還建議使用JSON進行數據傳輸,因為使用Javascript非常容易。
我認為您正在尋找類似於下面的代碼:
public IEnumerable<Question> 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<Question>();
questions.Add(new Question());
return questions;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.