如何强制 C# Web 服务对象属性中的最大字符串长度?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/212821/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How force a maximum string length in a C# web service object property?
提问by Joshua Turner
In this class for example, I want to force a limit of characters the first/last name can allow.
例如,在这个类中,我想强制限制名字/姓氏允许的字符数。
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
Is there a way to force the string limit restriction for the first or last name, so when the client serializes thisbefore sending it to me, it would throw an error on their side if it violates the lenght restriction?
有没有办法强制对名字或姓氏进行字符串限制限制,因此当客户端在将其发送给我之前对其进行序列化时,如果它违反了长度限制,它会在他们这边抛出错误?
Update: this needs to be identified and forced in the WSDL itself, and not after I've recieved the invalid data.
更新:这需要在 WSDL 本身中进行识别和强制,而不是在我收到无效数据之后。
回答by Mitchel Sellers
COnvert the property from an auto property and validate it yourself, you could then throw an argument exception or something similar that they would have to handle before submission.
从自动属性转换属性并自己验证它,然后您可以抛出参数异常或类似的东西,他们必须在提交之前处理。
NOTE: if languages other than .NET will be calling you most likely want to be validating it on the service side as well. Or at minimun test to see how it would work in another language.
注意:如果 .NET 以外的语言会调用您,您很可能也希望在服务端对其进行验证。或者在最小测试中查看它如何在另一种语言中工作。
回答by Mark Cidade
You can apply XML Schema validation (e.g., maxLengthfacet) using SOAP Extensions:
您可以使用SOAP 扩展来应用 XML 架构验证(例如,maxLengthfacet):
[ValidationSchema("person.xsd")]
public class Person { /* ... */ }
<!-- person.xsd -->
<?xml version="1.0"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="Person" type="PersonType" />
<xsd:simpleType name="NameString">
<xsd:restriction base="xsd:string">
<xsd:maxLength value="255"/>
</xsd:restriction>
</xsd:simpleType>
<xsd:complexType name="PersonType">
<xsd:sequence>
<xsd:element name="FirstName" type="NameString" maxOccurs="1"/>
<xsd:element name="LastName" type="NameString" maxOccurs="1"/>
</xsd:sequence>
</xsd:complexType>
</xsd:schema>
回答by Jason
necro time... It worth mentioning though.
死灵时间...不过值得一提。
using System.ComponentModel.DataAnnotations;
public class Person
{
[StringLength(255, ErrorMessage = "Error")]
public string FirstName { get; set; }
[StringLength(255, ErrorMessage = "Error")]
public string LastName { get; set; }
}