InvalidCastException将Json字符串映射到Guid属性

时间:2013-07-23 17:31:38

标签: c# json asp.net-web-api guid .net

有了POCO:

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

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

和这个Json:

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

我得到了一个例外:

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()

将其称为ASP.NET Web API控制器:

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

如果将属性类型的Guid更改为字符串,一切正常,但我想要Guid。是否支持这种情况?

1 个答案:

答案 0 :(得分:3)

在异常堆栈跟踪中没有明显的问题,问题不在于映射,而是在验证属性修饰中:

[Required]
[StringLength(36)] // NO-NO!
public Guid AppKey { get; set; }