代码之家  ›  专栏  ›  技术社区  ›  kovac

在Asp.Net核心Web API的反序列化过程中,未验证用[DataMember]修饰的数据

  •  0
  • kovac  · 技术社区  · 7 年前

    [DataContract]
    public class MyDTO
    {
        [DataMember(IsRequired)]
        public string MyProperty { get; set; }
    }
    

    POST 请求而不 MyProperty ,我没有得到任何例外。

    编辑:

    我的控制器看起来像:

    [HttpPost]
    public async Task<IActionResult> Add([FromForm] MyDTO newDTO)
    {
        if (!this.ModelState.IsValid)
        {
            var errors = this.GetModelStateErrors();
            return this.BadRequest();
        }
    
        try
        {
            var newDo = this.mapper.Map<MYDTO, MyDO>(newDto);
            await this.dataManager.InsertAsync(this.myDbContext, newDo);
    
            return this.StatusCode(201);
        }
        catch (ValidationException e)
        {
            return this.BadRequest(e.Message);
        }
        catch (Exception e)
        {
            return this.StatusCode(500, "Unspecified error occurred while processing request.");
        }
    }
    

    我也在Db上下文中对DO进行验证。我想验证DTO。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Mohamed Elrashid    7 年前
    public class MyDTO
    {
        [System.ComponentModel.DataAnnotations.Required]
        public string MyProperty { get; set; }
    }