当dto具有数据注释时,PutAsJsonAsync不起作用

时间:2013-05-07 11:45:55

标签: c# asp.net-web-api dotnet-httpclient

我看到HttpClient和Web API与我的DTO有一些奇怪的行为。当我为我的属性准备好数据注释时,HttpClient.PutAsJsonAsync()不起作用。我无法在Web API端收到任何内容。一些代码解释:

我的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)
};

1 个答案:

答案 0 :(得分: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