简体   繁体   English

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

[英]How to return a list of objects as an IHttpActionResult?

I'm new to ASP.NET webapi and I can't find a way to return a list of objects queried by id. 我是ASP.NET webapi的新手,我找不到返回id查询对象列表的方法。

This is my controller method for the GET request. 这是我的GET请求的控制器方法。 I want to return all the questions which have a specified questionnaireId passed via url. 我想返回所有通过网址传递指定问卷的问题。

I tried this: 我试过这个:

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

This is my Question class: 这是我的问题类:

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

But on return questions it shows the compiler error: 但在return questions它显示编译器错误:

Cannot implicitly convert type System.Linq.IQueryable<finah_backend.Models.Question> to System.Web.Http.IHttpActionResult . 无法将System.Linq.IQueryable<finah_backend.Models.Question>类型隐式转换为System.Web.Http.IHttpActionResult An explicit conversion exists (are you missing a cast?) 存在显式转换(您是否错过了演员?)

I want to get a list of questions returned in JSON queried on questionnaireId, which is passed via a url ie api/questions/2 ==> gives me back all the questions with questionnaireId = 2. 我想得到一份问卷清单,这些问题是在问卷调查中查询的,这是通过网址传递的,即api / questions / 2 ==>通过问卷调查表ID = 2给我回复所有问题。

You're using the [ResponseType] attribute, but that's only for generating documentation, see MSDN: ResponseTypeAttribute Class : 您正在使用[ResponseType]属性,但这仅用于生成文档,请参阅MSDN:ResponseTypeAttribute类

Use this to specify the entity type returned by an action when the declared return type is HttpResponseMessage or IHttpActionResult. 当声明的返回类型为HttpResponseMessage或IHttpActionResult时,使用此选项指定操作返回的实体类型。 The ResponseType will be read by ApiExplorer when generating ApiDescription. 生成ApiDescription时,ApiExplorer将读取ResponseType。

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<Question> GetQuestion(int questionnaireId)

Or, if you want it to be async: 或者,如果您希望它是异步的:

public async Task<IEnumerable<Question>> GetQuestion(int questionnaireId)

Or wrap the result in an IHttpActionResult , which the method Request.CreateResponse<T>() does: 或者将结果包装在IHttpActionResultRequest.CreateResponse<T>()执行此操作:

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

The latter is done for you if you call the ApiController.Ok() method: 如果你调用ApiController.Ok()方法,后者就完成了:

return Ok(questions);

Just simply return it like this, you need to use one of the nice methods that ApiController now supplies. 只需简单地返回它,你需要使用ApiController现在提供的一个很好的方法。

This will return a status code of 200 along with your questions collection. 这将返回状态代码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);
}

First of all do not use the entity directly for providing data. 首先,不要直接使用实体来提供数据。 Create a DTO for your entities: 为您的实体创建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
  }
}

Then your GET method could look like this: 然后你的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();
}

I also recommend to use JSON for data transfer since it is quite ease to use with Javascript. 我还建议使用JSON进行数据传输,因为使用Javascript非常容易。

I think that you are looking for some code similar to below: 我认为您正在寻找类似于下面的代码:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM