我在 C# ASMX Web 服务中有以下类,而不是 MVC 或 Web 表单项目。
public class Hotel
{
public int HotelId {get;set;}
public string Name {get;set;}
public Room[] Room { get; set; }
[Range(0, 12, ErrorMessage = "Rating must be between 1 and 5")]
public int Rating {get;set:}
}
public class Room
{
[Required]
public int RoomId {get;set;}
[Required]
[StringLength(175)]
public string Name {get; set;}
}
使用 System.ComponentModel.DataAnnotations,因为我能够像上面那样有效?如果是这样,我如何获得验证错误的响应?
此外,当服务启动时,我会读入如下所示的 Json 数据对象。
oHotelRequest = JsonConvert.DeserializeObject<Hotel>(sJson);
HotelResponse oHotelResponse = BookingAPI.Hotel.Get(oHotelRequest);
return JsonConvert.SerializeObject(oHotelResponse);
或者我可以在反序列化对象时进行验证吗?
最佳答案
你可以看看这个网页:http://odetocode.com/blogs/scott/archive/2011/06/29/manual-validation-with-data-annotations.aspx
关于c# - 如何验证存储在 C# 类中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17921919/