当请求模型实际上无效时,ModelState有效

时间:2019-04-01 20:45:31

标签: c# asp.net-core asp.net-core-webapi model-binding modelstate

我正在尝试验证API的POST请求中的请求模型。但是无论我在请求正文中发送的模型正确与否, <div style={{ height: "500px", width: "100%", overflow: "auto", borderStyle: "solid", borderWidth: 1, borderColor: "lightGray" }} > <Table> <TableHead> <TableRow> <TableCell padding="checkbox" style={{ position: "sticky", top: 0, backgroundColor: "white" }} > <Checkbox /> </TableCell> <TableCell style={{ position: "sticky", top: 0, backgroundColor: "white" }} > id </TableCell> <TableCell style={{ position: "sticky", top: 0, backgroundColor: "white" }} > name </TableCell> </TableRow> </TableHead> <TableBody> {data.map(row => ( <TableRow key={row.id} hover> <TableCell padding="checkbox"> <Checkbox /> </TableCell> <TableCell>{row.id}</TableCell> <TableCell>{row.name}</TableCell> </TableRow> ))} </TableBody> </Table> </div> 始终显示有效。无效的请求正文(如我更改了字段名称或修改了特定属性的字段类型)。

代码如下:

ValidateModelStateAttribute类:

ModelState.IsValid

控制器类:

public class ValidateModelStateAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext context)
    {
        if (!context.ModelState.IsValid)
        {
            context.Result = new BadRequestObjectResult(context.ModelState);
        }
    }
}

Book Model类:

[HttpPost("Search")]
[Produces("application/json")]
public async Task<IActionResult> SearchBook([FromBody]Book searchRequest)
{
    if (searchRequest!= null && !ModelState.IsValid)
    {
        return BadRequest();
    }
    return new ObjectResult("Book!");
}

在Startup.cs类中:

[DataContract]
[Serializable]
public class Book
{
    [Required]
    [DataMember]
    public string BookId;
    [Required]
    [DataMember]
    public string BookName;       
}

当我在 services.AddMvc(options => { options.Filters.Add(typeof(ValidateModelStateAttribute)); }) 类中进行调试时,ValidateModelStateAttribute字段始终为true,而isValid始终为空。

有人知道为什么吗?

1 个答案:

答案 0 :(得分:4)

为了使MVC中的模型绑定(以及用于JSON主体的幕后使用的JSON.NET)正常工作,您的BookIdBookName成员必须为属性,但它们当前是字段。它应该是这样的:

public class Book
{
    [Required]
    public string BookId { get; set; }

    [Required]
    public string BookName { get; set; }
}

(我还删除了DataContractDataSerializableDataMember,因为这些不必要。)

相关问题