Подтвердить что ты не робот

Как исключить определенные свойства из привязки в ASP.NET Web Api

Как я могу исключить определенные свойства или явно указать, какие свойства модели должны быть привязаны связующим веществом 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));
}
4b9b3361

Ответ 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.

Ответ 2

Вы можете попробовать 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
}