Serialization Exception Exception on ServiceStack

I use ServiceStack to create a service that accepts a request and HTML form (POSTed). One of the properties of the DTO is Enum, and when the input does not match the members of Enum, I get the following exception:

Error occured while Processing Request: KeyValueDataContractDeserializer: Error converting to type: Requested value 'MyValue' was not found. System.Runtime.Serialization.SerializationException: KeyValueDataContractDeserializer: Error converting to type: Requested value 'MyValue' was not found. ---> System.ArgumentException: Requested value 'MyValue' was not found. at System.Enum.TryParseEnum(Type enumType, String value, Boolean ignoreCase, EnumResult& parseResult) at System.Enum.Parse(Type enumType, String value, Boolean ignoreCase) at ServiceStack.ServiceModel.Serialization.StringMapTypeDeserializer.PopulateFromMap(Object instance, IDictionary`2 keyValuePairs) 

How to catch this exception and handle it myself in my service code?

+4
source share
1 answer

There are several ways to deal with this situation:

You can make the DTO Enum property a string (since everything can successfully deserialize to a string :), and then manually convert it manually.

 using ServiceStack.Common; //ToEnum<> is an extension method public class RequestDto { public string EnumString { get; set; } } public override object OnGet(RequestDto request) { MyEnum defaultValue = MyEnum.None; try { defaultValue = request.EnumString.ToEnum<MyEnum>(); } catch {} } 

Another option is to completely remove it from the DTO request and get the value manually from the IHttpRequest context, for example:

 public class RequestDto {} public override object OnGet(RequestDto request) { MyEnum enumValue = MyEnum.DefaultValue; try { var enumStr = base.RequestContext.Get<IHttpRequest>().QueryString["EnumString"]; enumValue = enumStr.ToEnum<MyEnum>(); } catch {} } 

I generally do not recommend using DTO enumerations for many reasons, the main one being XML / SOAP endpoints, XSD treats them as a limited set of values, which is a pain when trying to iteratively develop your web services, since you need to reuse clients add new value.

By convention, as I do this, you need to have all the enumerations as strings, but provide some metadata in the DTO that indicates the target type (which helps in the navigation and metadata tools of VS.NET/R#).

 public class RequestDto { [References(typeof(MyEnum))] public string EnumString { get; set; } } 
+3
source

Source: https://habr.com/ru/post/1381822/


All Articles