WebAPI 返回消息报错“无法将类型为“System.Int32”的对象强制转换为类型“System.String”
“ExceptionMessage”: “无法将类型为“System.Int32”的对象强制转换为类型“System.String”。”,
//API控制器[RoutePrefix("api/users")]public class UsersController : ApiController{[HttpPost][Route("login")]public IHttpActionResult Login(LoginViewModel model){if (ModelState.IsValid){return Ok(new ResponseData());}else{return Ok(new ResponseData() { Code = 500, ErrorMessage = "账号密码有误" });}}}
//用来验证登录的模型类public class LoginViewModel{[Required][EmailAddress][StringLength(maximumLength:100,MinimumLength =5)]public string LoginName { get; set; }[Required][StringLength(maximumLength: 40, MinimumLength = 6)]public int LoginPwd { get; set; }}
//回应类public class ResponseData{public int Code { get; set; } = 200;public Object Data { get; set; }public string ErrorMessage { get; set; }}
PostMan测试
报错:
原因:Model类的过滤器设置和属性数据类型有冲突
改正:
[Required][StringLength(maximumLength: 40, MinimumLength = 6)]//public int LoginPwd { get; set; }public string LoginPwd { get; set; }
[StringLength(maximumLength:100,MinimumLength =5)]
该特性应应用于实体类的string类型的属性上
如出现上例类似的类型冲突,则会在类型转换时报错"ExceptionMessage": "无法将类型为“System.Int32”的对象强制转换为类型“System.String”。",