首页 > 解决方案 > 如何在 Asp.net C# 中验证 Webservice 中的输入字段?

问题描述

我正在用 Asp.net C# 编写一个 Web 服务,我需要验证 Web 服务本身的字段,我该怎么做?我在下面给出了一个小例子

 public class Pack{
    public double Weight { get; set; }
    public double Height { get; set; }  
}

[WebMethod]
public string CreateShip(Pack pk){

  List<Ship> Sh = new List<Ship>();
  sh.weight=pk.Weight;

}

这里列表来自第三方 api,我正在为第三方重量属性分配重量,但在第三方他们只接受 50 公斤,所以在分配时我需要在网络服务中检查重量我该怎么做?

标签: c#asp.netrestweb-servicessoap

解决方案


您可以像下面的解决方法一样验证您的属性:

public class Pack {
    private double _weight;
    public double Weight {
        get = >_weight;
        set {
            if (_weight > 50) throw new Exception("Weight is limited up to 50k.");
            _weight = value;
        }
    }
    public double Height {
        get;
        set;
    }
}

[WebMethod]
public string CreateShip(Pack pk) {

    List < Ship > Sh = new List < Ship > ();
    sh.weight = pk.Weight;

}

推荐阅读