2013-05-07 67 views
1

我看到HttpClient和Web API與我的DTO存在一些奇怪的行爲。當我爲我的屬性使用數據註釋時,HttpClient.PutAsJsonAsync()不起作用。我無法在Web API端收到任何內容。一些代碼來解釋:當dto具有數據註釋時,PutAsJsonAsync不起作用

我的MVC 4網頁調用Web API使用此代碼:

using (var client = new HttpClient()) 
{ 
    var response = client.PutAsJsonAsync(uri+"/"+MyObject.Id, MyObject).Result; 
    response.EnsureSuccessStatusCode(); // Returns 500 when i use MyObject with annotations        
} 

的Web API控制器代碼接收。請注意,這甚至不是觸發時爲MyObject有註釋:

public MyObject Put(MyObject myObject) 
{ 
     try 
     { 
      if (myObject == null) throw new NullReferenceException(); 
     } 
     catch (Exception e) 
     { 
      throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.BadRequest)); 
     } 
} 

myObject的DTO時,它的工作原理:

public class MyObject 
{ 
    public int Id { get; set; } 
    public Nullable<int> AuditProgramId { get; set; } 
    public string Title { get; set; } 
    public System.DateTime StartDate { get; set; } 
    public System.DateTime EndDate { get; set; } 
} 

myObject的DTO的時候它不工作:

public class MyObject 
{ 
    public int Id { get; set; } 
    public Nullable<int> AuditProgramId { get; set; } 
    [Required] 
    public string Title { get; set; } 
    [Required, DataType(DataType.Date)] 
    public System.DateTime StartDate { get; set; } 
    [Required, DataType(DataType.Date)] 
    public System.DateTime EndDate { get; set; } 
} 

任何想法?

更新1

它與這些值沒有註釋,但無法與註釋:

var myObj = new MyObject { 
    Id=4, 
    Title="Test Title", 
    StartDate=DateTime.Today, 
    EndDate=DateTime.Today.AddDays(2) 
}; 
+0

您可以包括失敗的對象的樣本? '新的MyObject {...}' – 2013-05-07 11:50:51

回答

3

我可以攝製您的方案,並在異常消息實際上提供了一個解決這個問題:

Property 'StartDate' on type 'MvcApplication.Model.MyObject' is invalid. Value-typed properties marked as [Required] must also be marked with [DataMember(IsRequired=true)] to be recognized as required. Consider attributing the declaring type with [DataContract] and the property with [DataMember(IsRequired=true)].

我已經修改了我MyObject相應的課程,我得到你的方案工作。

[DataContract] 
public class MyObject 
{ 
    [DataMember] 
    public int Id { get; set; } 

    [DataMember] 
    public Nullable<int> AuditProgramId { get; set; } 

    [DataMember] 
    [Required] 
    public string Title { get; set; } 

    [Required, DataType(DataType.Date)] 
    [DataMember(IsRequired = true)] 
    public System.DateTime StartDate { get; set; } 

    [Required, DataType(DataType.Date)] 
    [DataMember(IsRequired = true)] 
    public System.DateTime EndDate { get; set; } 
} 

僅供參考,與本方案中的一個錯誤是最近固定,使事情變得更簡單:Overly aggressive validation for applying [DataMember(IsRequired=true)] to required properties with value types