c# - ReadAsAsync - 抛出异常类型是接口(interface)或抽象类,无法实例化

标签 c# asp.net-web-api

我有以下代码,尝试从 Web api 服务获取 Appication 对象。我收到以下异常:

InnerException = {"Could not create an instance of type BusinessEntities.WEB.IApplicationField. Type is an interface or abstract class and cannot be instantated. Path '_applicationFormsList[0]._listApplicationPage[0]._listField[0]._applicationFieldID', line 1, position 194."}.

我不明白为什么将 FieldList 更改为 Interface 会导致反序列化对象时出现问题。非常感谢任何指点。

Task<HttpResponseMessage> task = HttpClientDI.GetAsync(someUri);
HttpResponseMessage response = task.Result;

HttpClientHelper.CheckResponseStatusCode(response);

try
{
    Application application = response.Content.ReadAsAsync<ApplicationPage>().Result;
    return application;
}
catch (Exception ex)
{
    throw new ServiceMustReturnApplicationException(response);
}



[Serializable]
public class ApplicationPage
{
    #region Properties
    public int PageOrder { get; set; }
    public string Title { get; set; }
    public string HtmlPage { get; set; }
    public int FormTypeLookupID { get; set; }

    List<IApplicationField> _listField = new List<IApplicationField>(); 
    public List<IApplicationField> FieldList
    {
        get { return _listField; }
        set { _listField = value; }
    }
}

最佳答案

您需要为要反序列化的类的所有接口(interface)指定具体类,以便在反序列化过程中为这些接口(interface)创建实例。

这样做,可以通过为json.net创建自定义转换器来获取:

public class ApplicationFieldConverter : CustomCreationConverter<IApplicationField>
{
    public override IApplicationField Create(Type objectType)
    {
        return new FakeApplicationField();
    }
}

你的代码应该是:

string jsonContent= response.Content.ReadAsStringAsync().Result;
Application application = JsonConvert.DeserializeObject<Application>(jsonContent,
                                 new ApplicationFieldConverter());

注意:方法Content.ReadAsAsync<...>()在 ASP.NET Web API RC 中找不到,您使用的是 beta 版本吗?

关于c# - ReadAsAsync - 抛出异常类型是接口(interface)或抽象类,无法实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11748912/

相关文章:

C# 程序集在子域中创建实例

调用 web api 时 C# 不支持授权类型

asp.net-web-api - 从 NSwag swagger 中过滤架构

c# - 帮助 QueryOver 和 WhereExists

c# - Windbg 使用 TryGetValue 从字典中获取值

c# - C# 中的 KNXnetIP 实现

c# - 在同一解决方案中为 CurrentCulture 获取两个不同的值

asp.net - 我可以合并 SignalR 和 RESTful API 吗?

c# - ASP.NET中如何获取登录用户信息

c# - 这是什么意思?