我是Web API领域的新手 ASP.Net。对不起,如果这是一个愚蠢的问题。
我有以下 api 方法 -
[Route("api/v1/Location/Create")]
[HttpPost]
public IHttpActionResult Create(Location location)
{
if (!ModelState.IsValid)
{
return StatusCode(HttpStatusCode.BadRequest);
}
return Ok();
}
public class Location
{
public int MCC { get; set; }
public int MNC { get; set; }
public int LAC{ get; set; }
public int CellId { get; set; }
}
如果我从客户端发送字符串值,它仍然返回StatusCode 200
.
我在这里缺少什么?
您尚未在位置类上放置任何数据注记。尝试添加[Required]
属性之一的数据注释。
按如下方式修改你的类-
using System.ComponentModel.DataAnnotations;
public class Location
{
[Required()]
public int MCC { get; set; }
[Required()]
public int MNC { get; set; }
[Required()]
public int LAC{ get; set; }
[Required()]
public int CellId { get; set; }
}
ModelState.IsValid
正在检查数据模型验证,当每个文件都由[Required]
注释时。