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

本文关键字:PutAsJsonAsync 不起作用 注释 数据 dto | 更新日期: 2023-09-27 18:12:31

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

我的MVC 4 web页面调用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)
};

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

我可以重现您的场景,异常消息实际上提供了这个问题的解决方案:

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)]的验证过于激进