1

我在 DTO 中看到 HttpClient 和 Web API 的一些奇怪行为。当我的属性有数据注释时,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)
};
4

1 回答 1

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

仅供参考,最近修复了与此场景相关的错误以使事情变得更简单: 将 [DataMember(IsRequired=true)] 应用于具有值类型的所需属性的过度积极验证

于 2013-05-08T19:18:34.097 回答