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



拥有这些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。是否支持这种情况?

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

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

相关内容

  • 没有找到相关文章

最新更新