如何验证 C# 类中存储的数据

nei*_*ldt 5 c# validation asmx

我在 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;}
}
Run Code Online (Sandbox Code Playgroud)

使用 System.ComponentModel.DataAnnotations,因为我能够像上面那样有效?如果是这样,我如何获得验证错误的响应?

此外,当服务启动时,我会读入 Json 数据对象,如下所示。

  oHotelRequest = JsonConvert.DeserializeObject<Hotel>(sJson);
  HotelResponse oHotelResponse = BookingAPI.Hotel.Get(oHotelRequest);
  return JsonConvert.SerializeObject(oHotelResponse);
Run Code Online (Sandbox Code Playgroud)

或者我可以在反序列化对象时进行验证吗?