Max*_*icu 4 c# asp.net asp.net-web-api asp.net-web-api2
我有这个模型:
public class Quiz
{
public int Id { get; set; }
public string Title { get; set; }
public int CurrentQuestion { get; set; }
[JsonIgnore]
public virtual ICollection<Question> Questions { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
其中[JsonIgnore]告诉 JSON Serializer 忽略此字段(问题)。所以,我正在执行一个操作,返回没有问题的序列化测验。我必须实施另一个操作,该操作将返回所有字段(包括问题)。我怎样才能做到这一点 ?我需要这两个动作。
最好不要从 API 返回域模型。更好的方法是创建视图模型类并返回它们。
因此,在您的示例中,您只需创建:
public class QuizViewModel
{
public int Id { get; set; }
public string Title { get; set; }
public int CurrentQuestion { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
并使用它从 API 返回数据。
显然,在一些较大的类中,创建复制所有属性的代码将是一场噩梦,但不用担心 - Automapper ( http://automapper.org/ ) 来救援!:)
//Best put this line in app init code
Mapper.CrateMap<Quiz, QuizViewModel>();
//And in your API
var quiz = GetSomeQuiz();
return Mapper.Map<QuizViewModel>(quiz);
Run Code Online (Sandbox Code Playgroud)
然后,您以相同的方式创建另一个带有 Questions 字段的视图模型类。