问题描述
我有 web api 3.0 解决方案,但我没有任何 UI。我的所有回复都只在邮递员那里查过。 对于输入验证,我使用了数据注释,但我在 post man 中看不到错误消息。请帮助我我犯了什么错误。
目前我收到如下错误信息:
{
"studentid": [
"Error converting value {null} to type 'system.int32'. Path 'studentid',line 2,position 26."
]
}
student Id is required.This cannot be null or blank
//[required (ErrorMessage = "student Id is required.This cannot be null or blank")]
//public int StudentId { get; set; }
到目前为止我做了什么:
-
我的模型
public class Employee { [required (ErrorMessage = "student Id is required.This cannot be null or blank")] public int StudentId { get; set; } [required (ErrorMessage = "Student name is required.This cannot be null or blank")] [StringLength(100,MinimumLength = 2)] public string FirstName { get; set; } [required] public string LastName { get; set; } [required (ErrorMessage = "Student age is required.This cannot be null or blank")] public int Age{ get; set; } }
-
我的控制器
[HttpPost("api/Student/Check")] public async Task Check([FromBody] students input) { if (!ModelState.IsValid) { returnBadRequest(Modelstate); } else { returnOk(); } }
-
为 ValidatorActionFilter.cs 创建了一个类
public class ValidatorActionFilter : IActionFilter { public void OnActionExecuting(ActionExecutingContext filterContext) { if (!filterContext.ModelState.IsValid) { filterContext.Result = new BadRequestObjectResult(filterContext.ModelState); } } public void OnActionExecuted(ActionExecutedContext filterContext) { } }
startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(options =>
{
options.Filters.Add(typeof(ValidatorActionFilter));
});
}
解决方法
您收到的邮递员错误是正确的。
默认情况下,int
数据类型不是 nullable
,因此如果您将 null
分配给 int
,则会出现错误。
您的 API 正在按预期工作,没有人应该将 null
或 string
传递给 int
数据类型,但是如果您希望 StudentId
使用 null
那就让它nullable
,像这样:
public class Employee
{
[Required (ErrorMessage = "student Id is required.This cannot be null or blank")]
public int? StudentId { get; set; }
//rest of your properties
}