Gri*_*der 14 c# asp.net asp.net-mvc asp.net-web-api asp.net-web-api2
如何排除某些属性,或明确指定Web Api模型绑定器应绑定哪些模型属性?类似于CreateProduct([Bind(Include = "Name,Category") Product product)ASP.NET MVC的东西,没有创建另一个模型类,然后从原始模型复制它的所有验证属性.
// 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));
}
Run Code Online (Sandbox Code Playgroud)
如果您使用 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
}
Run Code Online (Sandbox Code Playgroud)
对于 XML,您可以使用 DataContract 和 DataMember 属性。
有关两者的更多信息,请访问asp.net 网站。
| 归档时间: |
|
| 查看次数: |
5176 次 |
| 最近记录: |