Joshua Turner
Joshua Turner

Reputation: 1049

How force a maximum string length in a C# web service object property?

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 this before 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.

Upvotes: 4

Views: 15729

Answers (3)

Mark Cidade
Mark Cidade

Reputation: 99957

You can apply XML Schema validation (e.g., maxLength facet) using SOAP Extensions:

[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>

Upvotes: 3

Jason
Jason

Reputation: 111

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; }
}

Upvotes: 11

Mitchel Sellers
Mitchel Sellers

Reputation: 63126

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.

Upvotes: 0

Related Questions