How to return a list of objects as an IHttpActionResult?

前端 未结 4 1442
伪装坚强ぢ
伪装坚强ぢ 2021-02-08 09:19

I\'m new to ASP.NET webapi and I can\'t find a way to return a list of objects queried by id.

This is my controller method for the GET request. I want to return all the

4条回答
  •  别那么骄傲
    2021-02-08 09:38

    First of all do not use the entity directly for providing data. Create a DTO for your entities:

    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
      }
    }
    

    Then your GET method could look like this:

    // 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();
    }
    

    I also recommend to use JSON for data transfer since it is quite ease to use with Javascript.

提交回复
热议问题