[英]ASP.NET Core 2.2 Web API controller inherited from Object class (not from Controller class)
[英]inherited class and properties not included in JSON result from ASP.NET Core API
我有一个简单的模型,我尝试将其序列化为 JSON,但某些属性未包含在结果中。 当我的对象从基类继承时,基类的属性不会出现在 json 中。
在 JSON 字符串中“searchModel”是 {}
SearchModelBase.cs :
public interface ISearchModelBase
{
SearchTypes Type { get; set; }
string SearchString { get; set; }
}
public abstract class SearchModelBase : ISearchModelBase
{
public SearchModelBase(SearchTypes type, string searchString)
{
this.Type = type;
this.SearchString = searchString;
}
public SearchTypes Type { get; set; }
public string SearchString { get; set; }
}
public enum SearchTypes
{
User,
Site
}
AssetsDefaultSearchModel.cs :
public interface IAssetsDefaultSearchModel : ISearchModelBase
{
}
public class AssetsDefaultSearchModel : SearchModelBase, IAssetsDefaultSearchModel
{
public AssetsDefaultSearchModel(SearchTypes type, string searchString) : base(type, searchString)
{
}
}
JSON :
{
"items": [
{
"displayName": "FFU Samarin",
"data": {
"appId": 3,
"displayName": "FFU Samarin",
..........
在 Visual Studio 中,集合中的每一项都包含 AssetsDefaultSearchModel 和两个属性中的值:
在从 ISearchResultBase 派生的接口中,我必须使用 new 关键字定义一个新属性。 然后我返回一个从 IAssetsDefaultSearchResult 派生的对象(不复制类中的属性)并且它按预期工作。
public interface IAssetsDefaultSearchResult : ISearchResultBase
{
new ISearchModelBase SearchModel { get; }
string DisplayName { get; }
object Data { get; }
TagBuilder HtmlTag { get; }
}
将以下代码添加到您的 Startup.cs
services.AddControllers().AddNewtonsoftJson();
你可以使用Microsoft.AspNetCore.Mvc.NewtonsoftJson NuGet 包
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.