当前位置: 代码迷 >> 综合 >> WebAPI 返回消息报错-强制转换
  详细解决方案

WebAPI 返回消息报错-强制转换

热度:8   发布时间:2023-11-26 03:40:07.0

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测试

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ikeuBt0o-1639398962903)(C:\Users\瞌睡遇上枕\Desktop\postman测试)]

报错:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-dKlfCGR0-1639398962904)(C:\Users\瞌睡遇上枕\Desktop\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”。",