2012-09-03 38 views
9

Có thể cho một phương pháp điều khiển để xử lý tất cả các mục đã đăng xuất phát từ một lớp cơ sở cụ thể không? Ý tưởng là để có thể gửi các lệnh bằng cách gửi chúng đến một điểm cuối. Khi tôi thử như sau, tham số "cmd" trong phương thức Post luôn là null.ASP.New Web API - Mô hình ràng buộc và thừa kế?

Ví dụ

//the model: 
public abstract class Command{ 
    public int CommandId{get; set;} 
} 
public class CommandA:Command{ 
    public string StringParam{get; set;} 
} 
public class CommandB:Command{ 
    public DateTime DateParam{get; set;} 
} 

//and in the controller: 
    public HttpResponseMessage Post([FromBody]Command cmd) 
    { 
     //cmd parameter is always null when I Post a CommandA or CommandB 
     //it works if I have separate Post methods for each Command type 
     if (ModelState.IsValid) 
     { 
      if (cmd is CommandA) 
      { 
       var cmdA = (CommandA)cmd; 
       // do whatever 
      } 
      if (cmd is CommandB) 
      { 
       var cmdB = (CommandB)cmd; 
       //do whatever 
      } 

      //placeholder return stuff 
      var response = Request.CreateResponse(HttpStatusCode.Created); 
      var relativePath = "/api/ToDo/" + cmd.TestId.ToString(); 
      response.Headers.Location = new Uri(Request.RequestUri, relativePath); 
      return response; 
     } 
     throw new HttpResponseException(HttpStatusCode.BadRequest); 
    } 

Một lần nữa, khi tôi thử phương pháp này là phương pháp bài được gọi, nhưng tham số luôn luôn là null từ khuôn khổ. Tuy nhiên nếu tôi thay thế nó bằng một phương thức Post với một kiểu tham số CommandA cụ thể, nó hoạt động.

Là những gì tôi đang cố gắng? Hay mọi loại tin nhắn đều cần một phương thức xử lý riêng trong bộ điều khiển?

Trả lời

Các vấn đề liên quan