【问题标题】:Why Web Api include properties in response that are not projected为什么 Web Api 在响应中包含未预测的属性
【发布时间】:2014-08-01 14:20:08
【问题描述】:

我有一个视图模型

public class MyViewModel
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Position { get; set; }
        public string Email { get; set; }
        public string Office { get; set; }
        public DateTime? StartDate { get; set; }
        public int? Age { get; set; }
        public int? Salary { get; set; }
        public int? Extn { get; set; }
    }

我正在对我的实体进行投影

 public List<ViewModel.StaffViewModel> GetAll()
        {
            var context = new GistDemoDbEntities();

            var model = context.Staff
                .Select(s => new ViewModel.StaffViewModel
                {
                    FirstName = s.FirstName,
                    LastName = s.LastName,
                    Position = s.Position,
                    Salary = s.Salary
                }).ToList();

            return model;
        }

并使用 Web Api 以 json 形式返回,但作为响应,我发现它还包括其他属性,这些属性在视图模型中定义为 vlaue null。我只想拥有我需要的那些属性,这怎么可能?

【问题讨论】:

    标签: entity-framework-6 asp.net-web-api2


    【解决方案1】:

    您可以:

    • 从您的 ViewModel 中删除它们,视图模型应该只包含 反正你打算用什么。

    • 在您的属性上使用 [JsonIgnore] 以防止 JSON.Net 映射 他们。

    Json Ignore是一个属性,看这里;

    http://james.newtonking.com/json/help/index.html?topic=html/SerializationAttributes.htm

    【讨论】:

    • 实际上,我确实希望在我的一个视图中公开一些属性,而在其他视图中我想要所有这些属性。这就是为什么我创建了一个包含所有属性的视图模型。无论如何,我只能显示投影实体作为响应?
    • 用你需要的属性创建另一个视图模型。
    猜你喜欢
    • 2016-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-11
    相关资源
    最近更新 更多