2015-03-20 16 views
8

ASP.NET webapi konusunda yeniyim ve id tarafından sorgulanan nesnelerin bir listesini döndürmenin bir yolunu bulamıyorum.Nesnelerin bir listesi nasıl IHttpActionResult olarak döndürülebilir?

Bu, GET isteği için denetleyici yöntemimdir. URL ile iletilen belirli bir anketi olan tüm soruları geri vermek istiyorum.

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

Bu benim Soru sınıftır:

Bu çalıştı

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

Ama return questions üzerine bu derleyici hata gösterir:

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?)

Ben bir listesini almak istiyorum JSON içinde döndürülen soruların anketi sorgulandı, bir URL ile iletildi, yani api/question/2 ==> questionnaireId ile beni geri tüm sorular = 2.

+1

Hata nedir veya herhangi bir istisna aldınız mı?Bence 'GetQuestion' yönteminiz, aslında geri döndüğünüzle eşleşmeyen dönüş türünden dolayı derlenmeyecektir. –

+0

'System.Winq.IQueryable ' türünün 'System.Web.Http.IHttpActionResult' türüne dolaylı olarak dönüştürülemiyor. Açık bir dönüşüm var (bir dökümün eksik mi?) – Rick

cevap

11

Sen [ResponseType] kullandığınızı, ama bu sadece belgeler oluşturmak için, MSDN: ResponseTypeAttribute Class görecek: artık gerekli olmadığı sürece,

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.

Sen dönüş türünü değiştirebilirsiniz ya (ve niteliğini kaldırmak

: Eğer zaman uyumsuz olmasını istiyorsanız,

public IEnumerable<Question> GetQuestion(int questionnaireId) 

Veya: döndürme türü belgeler) fiili imza elde edilecek

Veya, bir IHttpActionResult sonucu sarmak hangi yapar Request.CreateResponse<T>() yöntemi:

return Ok(questions); 
+0

İade türünü "public Task > GetQuestion (int questionnaireId)" olarak değiştirdim, ancak yine de hatayla karşılaşıyorum: "System.Linq.IQueryable türünü" System.Web "için dolaylı olarak dönüştüremiyor. Http.IHttpActionResult'. Açık bir dönüşüm var (bir dökümün eksik mi?) ' – Rick

+0

@Fairbreath, düzenlemeye bakın. Sentaksları karıştırıyorsun. 'Public IEnumerable <> 'veya' public async Task > 'seçeneğini kullanın. – CodeCaster

0

Ben aşağıda benzer bazı kod arıyoruz düşünüyorum: Her şeyden

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

İlk verilerini sağlamak için doğrudan varlık kullanmayın. sizin varlıklar için bir DTO oluşturun:

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

Sonra GET yöntemi bu gibi görünebilir:

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

Ben de oldukça Javascript ile kullanma kolaylığı olduğu için veri aktarımı için JSON kullanımı önerilir.

+0

Oh, bunu unutma, sadece Yanıtlarınızı bir HttpResonseMessage içinde sarmala. İade Request.CreateResponse (HttpStatusCode.OK, iade edilecek nesneniz); – Jazjef

6

Sadece basit gibi geri: Eğer ApiController.Ok() yöntemini çağırırsanız ikincisi sizin için yapılır

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

Bu, şimdi ApiController'ın sağladığı güzel yöntemlerden birini kullanmanız gerekir.

Bu, soru koleksiyonunuzla birlikte 200 durum kodu döndürecektir.

[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

_ "Sistem.Web.Http.Results.OkResult' türünü dolaylı olarak" System.Threading.Tasks.Task '" _ olarak değiştiremiyor. OP, "async" değiştiricisini eksik. – CodeCaster

+0

Düzenlendi ... Ancak bu düşüşe değer miydi? – BenjaminPaul

+1

Evet, bir derleyici hatası çözmeye çalışırken OP başka bir derleyici hatası ile yardımcı olmaz. Ayrıca, cevabınıza eklenen "async" i belirtmek isteyebilirsiniz. – CodeCaster

İlgili konular