Pregunta

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?

¿Fue útil?

Solución

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; }
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top