如何排除某些属性,或明确指定哪些模型属性应由 Web Api 模型绑定(bind)器绑定(bind)?类似于 ASP.NET MVC 中的 CreateProduct([Bind(Include = "Name,Category") Product product)
,无需创建另一个模型类,然后从原始模型类复制所有验证属性模型。
// EF entity model class
public class User
{
public int Id { get; set; } // Exclude
public string Name { get; set; } // Include
public string Email { get; set; } // Include
public bool IsAdmin { get; set; } // Include for Admins only
}
// HTTP POST: /api/users | Bind Name and Email properties only
public HttpResponseMessage Post(User user)
{
if (this.ModelState.IsValid)
{
return this.Request.CreateErrorResponse(this.ModelState);
}
this.db.Users.Add(user);
this.db.SaveChanges();
return this.Request.CreateResponse(HttpStatusCode.OK));
}
// HTTP POST: /api/admin/users | Bind Name, Email and IsAdmin properties only
public HttpResponseMessage Post(User user)
{
if (!this.ModelState.IsValid)
{
return this.Request.CreateErrorResponse(this.ModelState);
}
this.db.Users.Add(user);
this.db.SaveChanges();
return this.Request.CreateResponse(HttpStatusCode.OK));
}
最佳答案
如果您使用的是 JSON,则可以使用 [JsonIgnore]
属性来装饰您的模型属性。
public class Product
{
[JsonIgnore]
public int Id { get; set; } // Should be excluded
public string Name { get; set; } // Should be included
public string Category { get; set; } // Should be included
[JsonIgnore]
public int Downloads { get; set; } // Should be excluded
}
对于 XML,您可以使用 DataContract 和 DataMember 属性。
有关两者的更多信息,请访问 asp.net website .
关于c# - 如何从 ASP.NET Web Api 中的绑定(bind)中排除某些属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23197210/