3

Having theese POCOs:

public class UserRegistration
{
    [Required]
    public ApiKey ApiKey { get; set; }
    ...
}

public class ApiKey 
{
    [Required]
    public Guid AppKey { get; set; }
    ...
}

and this Json:

{
    "apiKey": {
      "appKey": "D8B4DE20-5654-43B0-B3F6-FDA416087FDE"
    }
}

I'm getting an exception:

System.InvalidCastException: Unable to cast object of type 'System.Guid' to type 'System.String'.
at System.Web.Http.ApiController.d__b.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.Http.Dispatcher.HttpControllerDispatcher.d__0.MoveNext()

calling this an ASP.NET Web API controller:

public HttpResponseMessage Put([FromBody]UserRegistration userRegistration)
{
}

If change property type form Guid to string, all works fine, but I want Guid. Is such scenario supported?

abatishchev
  • 98,240
  • 88
  • 296
  • 433
  • 1
    This should be helpful http://stackoverflow.com/questions/13640463/json-net-exception-when-deserializing-an-array-of-guids – Ehsan Jul 23 '13 at 17:36
  • @EhsanUllah: Does it mean Guid is not supported and I need to accept string and then parse it manually? – abatishchev Jul 23 '13 at 18:28
  • The post linked above is talking about being unable to deserialize an array of guids directly - but you've got just this one guid on the object, right? Is the exception text complete btw? It's saying unable to cast Guid but it's not saying to which type - can you post the full message? – Joanna Derks Jul 23 '13 at 19:16
  • @JoannaTurban: Sorry, exception message turned out to be truncated. Fixed. Guid to String. – abatishchev Jul 23 '13 at 20:11
  • 1
    @EhsanUllah: actually it's supported pretty fine, see my own answer below. – abatishchev Jul 23 '13 at 20:47

1 Answers1

3

What is not obviously following from the exception stack trace, problem was not in mapping but in validation attribute decoration:

[Required]
[StringLength(36)] // NO-NO!
public Guid AppKey { get; set; }
abatishchev
  • 98,240
  • 88
  • 296
  • 433