c# - 如何从 ASP.NET Web Api 中的绑定(bind)中排除某些属性

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

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

最佳答案

如果您使用的是 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 .

关于c# - 如何从 ASP.NET Web Api 中的绑定(bind)中排除某些属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23197210/

相关文章:

C# 为什么 "Flush"不强制字节通过网络流传输?

c# - Silverlight Xaml 中的 ComboBox IsEnabled 绑定(bind)问题

javascript - 从对话框中获取值并在后面的代码中使用它们

c# - 如何以安全的方式对 ç ö ü 进行编码?

c# - ASP.NET Identity 2 邮箱和用户名分离并使用邮箱登录

c# - 如何在网络上制作程序 "discoverable"?

c# - 为全息图 3D 风扇将视频转换为 .bin

asp.net - 如何在 asp :textbox 中放置提示

c# - 使用 IP 地址而不是本地主机时出现 HTTP 错误 400

asp.net - ASP.NET MVC 中的水印文本框