How do I exclude certain properties, or explicitly specify which model properties should be bound by Web Api model binder? Something similar to CreateProduct([Bind(Include = "Name,Category") Product product)
in ASP.NET MVC, without creating yet another model class and then duplicating all the validation attributes for it from the original model.
// 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));
}
If you're using JSON, you can use the [JsonIgnore]
attribute to decorate your model properties.
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
}
For XML, you can use the DataContract and DataMember attributes.
More info about both at the asp.net website.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With