How to return a list of objects as an IHttpActionResult?

前端 未结 4 1498
伪装坚强ぢ
伪装坚强ぢ 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:42

    You're using the [ResponseType] attribute, but that's only for generating documentation, see MSDN: ResponseTypeAttribute Class:

    Use this to specify the entity type returned by an action when the declared return type is HttpResponseMessage or IHttpActionResult. The ResponseType will be read by ApiExplorer when generating ApiDescription.

    You can either change your return type (and remove the attribute, as it isn't required anymore as the return type documentation will be generated from the actual signature):

    public IEnumerable GetQuestion(int questionnaireId)
    

    Or, if you want it to be async:

    public async Task> GetQuestion(int questionnaireId)
    

    Or wrap the result in an IHttpActionResult, which the method Request.CreateResponse() does:

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

    The latter is done for you if you call the ApiController.Ok() method:

    return Ok(questions);
    

提交回复
热议问题