如何在ASP.NET Web Api中从绑定中排除某些属性

时间:2014-04-21 12:12:46

标签: c# asp.net asp.net-mvc asp.net-web-api asp.net-web-api2

如何排除某些属性,或明确指定Web Api模型绑定器应绑定哪些模型属性?与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));
}

2 个答案:

答案 0 :(得分:1)

如果您正在使用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的更多信息。

答案 1 :(得分:0)

您可以尝试Exclude属性。

所以现在你的班级看起来像这样 -

public class Product
{
    [Exclude]
    public int Id { get; set; }          // Should be excluded
    public string Name { get; set; }     // Should be included
    public string Category { get; set; } // Should be included
    [Exclude]
    public int Downloads { get; set; }   // Should be excluded
}