Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exclude certain properties from binding in ASP.NET Web Api

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));
}
like image 728
Grief Coder Avatar asked Apr 21 '14 12:04

Grief Coder


1 Answers

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.

like image 125
GvM Avatar answered Sep 28 '22 05:09

GvM