【问题标题】:InvalidCastException mapping Json string onto Guid propertyInvalidCastException 将 Json 字符串映射到 Guid 属性
【发布时间】:2013-07-23 17:31:38
【问题描述】:

拥有这些 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。是否支持这样的场景?

【问题讨论】:

  • @EhsanUllah:这是否意味着不支持 Guid,我需要接受字符串然后手动解析它?
  • 上面链接的帖子是在谈论无法直接反序列化一组 guid - 但是您在对象上只有一个 guid,对吗?顺便说一句,异常文本是否完整?它说无法投射 Guid,但没有说是哪种类型 - 你能发布完整的消息吗?
  • @JoannaTurban:抱歉,异常消息被截断了。固定的。字符串指南。
  • @EhsanUllah:实际上它的支持很好,请参阅下面我自己的答案。

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


【解决方案1】:

从异常堆栈跟踪中没有明显看出什么,问题不在于映射,而在于验证属性装饰:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-27
    • 2011-08-19
    • 1970-01-01
    • 2015-07-09
    • 2021-11-17
    • 2016-11-24
    • 2020-02-23
    • 1970-01-01
    相关资源
    最近更新 更多