2015-03-20 11 views
8

Sono nuovo di ASP.NET webapi e non riesco a trovare un modo per restituire un elenco di oggetti interrogati da id.Come restituire un elenco di oggetti come IHttpActionResult?

Questo è il metodo del controller per la richiesta GET. Voglio restituire tutte le domande che hanno un questionario specifico passato tramite url.

ho provato questo:

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

Questa è la mia classe Domanda:

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

Ma return questions mostra l'errore del compilatore:

Cannot implicitly convert type System.Linq.IQueryable<finah_backend.Models.Question> to System.Web.Http.IHttpActionResult . An explicit conversion exists (are you missing a cast?)

voglio ottenere una lista di domande restituite in JSON interrogate su questionnaireId, che viene passato tramite un url ie api/questions/2 ==> dà Me Back tutte le domande con questionnaireId = 2.

+1

Che cosa è errror o hai ricevuto qualche eccezione?Penso che il tuo metodo 'GetQuestion' non verrebbe compilato a causa del tipo di restituzione non corrispondente con quello che hai effettivamente restituito. –

+0

Impossibile convertire implicitamente il tipo 'System.Linq.IQueryable ' in 'System.Web.Http.IHttpActionResult'. Esiste una conversione esplicita (ti manca un cast?) – Rick

risposta

11

Stai utilizzando l'attributo [ResponseType], ma questo è solo per la generazione di documentazione, vedere 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.

È possibile modificare il tipo di ritorno (e rimuovere l'attributo, in quanto non è più richiesto come la documentazione tipo di ritorno sarà generato dalla firma effettiva):

public IEnumerable<Question> GetQuestion(int questionnaireId) 

Oppure, se si vuole che sia asincrona:

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

o avvolgere il risultato in un IHttpActionResult, che il metodo Request.CreateResponse<T>() fa:

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

Quest'ultimo è fatto per voi, se si chiama il metodo ApiController.Ok():

return Ok(questions); 
+0

Ho cambiato il tipo di ritorno in 'public Task > GetQuestion (int questionnaireId)' ma ottengo ancora l'errore: 'Impossibile convertire implicitamente il tipo System.Linq.IQueryable in 'System.Web. Http.IHttpActionResult'. Esiste una conversione esplicita (ti manca un cast?) ' – Rick

+0

@Fairbreath vedi modifica. Stai mescolando le sintassi. Utilizzare 'public IEnumerable <>' o 'public async Task >'. – CodeCaster

0

Penso che siete alla ricerca di un po 'di codice simile al di sotto:

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

Prima di tutto non utilizzare l'entità direttamente per la fornitura di dati. Creare un DTO per le entità:

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

Allora il vostro metodo GET potrebbe essere la seguente:

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

vi consiglio anche di utilizzare JSON per il trasferimento dati dal momento che è abbastanza facilità per l'uso con Javascript.

+0

Oh dimentica questo, avvolgi le tue risposte in un messaggio HttpResonseMessage. return Request.CreateResponse (HttpStatusCode.OK, oggetto da restituire); – Jazjef

6

Basta semplicemente tornare piace questo, è necessario utilizzare uno dei bei metodi che ApiController ora fornisce.

Ciò restituirà un codice di stato di 200 insieme alla raccolta delle domande.

[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); 
} 
+1

_ "Impossibile convertire implicitamente il tipo' System.Web.Http.Results.OkResult' in 'System.Threading.Tasks.Task ' ". OP manca il modificatore 'async'. – CodeCaster

+0

Modificato ... Tuttavia valeva la pena del downvote? – BenjaminPaul

+1

Sì, quando si tenta di risolvere un errore del compilatore OP non viene aiutato con un altro errore del compilatore. Potresti anche voler indicare l'aggiunta 'async' nella tua risposta. – CodeCaster

Problemi correlati