使用数据注释进行C#MVC验证(数据库优先)

时间:2018-04-11 07:39:32

标签: c# asp.net-mvc asp.net-web-api2

所以我有一个像这样的控制器post动作的API:

public HttpResponseMessage Post(Model m){
  if(!ModelState.IsValid){
    return ApiRequest.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
  }
}

这是我的模特:

[MetadataType(typeof(Metadata))]
public partial class MyModel {

  private sealed class Metadata {

    [Required(ErrorMessage="Sample error msg.")]
    public string Field1 {get; set;}
    // ...other fields and foreign key fields here
  }

}

正如我在标题上所述,我首先使用数据库,这就是我创建partial类的原因,因为我的模型是自动生成的。

问题是当发生验证错误时,错误消息的结果JSON如下所示:

{
  e.Field1: "Error msg here...",
  e.Field2: "Error msg here...",
  e.DateField: "An error occurred" //This happens for any date type field even though i've specified an error message
  e: ["An error occurred", "An error occurred"] //This happens for the foreign key fields i.e. AnotherModelID, I got 2 which is why I think it has two error messages also
}

首先我想要的是删除JSON结果的e上的keys前缀。那么为什么即使我明确地输出错误消息,也会返回错误An error occurred?还有为什么外键字段不显示前缀e

由于

更新

经过更多研究,我认为如果有问题的字段的数据类型为{{1},则错误key只是字母e而不是e.FieldName。 }}。我已经测试了一个非外键int字段,它还会在“e only”键下添加错误。

0 个答案:

没有答案
相关问题