C# 如何从ASP.NET Web Api中的绑定中排除某些属性
如何排除某些属性,或者明确指定哪些模型属性应该由WebAPI模型绑定器绑定?类似于ASP.NET MVC中的C# 如何从ASP.NET Web Api中的绑定中排除某些属性,c#,asp.net,asp.net-mvc,asp.net-web-api,asp.net-web-api2,C#,Asp.net,Asp.net Mvc,Asp.net Web Api,Asp.net Web Api2,如何排除某些属性,或者明确指定哪些模型属性应该由WebAPI模型绑定器绑定?类似于ASP.NET MVC中的CreateProduct([Bind(Include=“Name,Category”)Product),无需创建另一个模型类,然后从原始模型复制其所有验证属性 // EF entity model class public class User { public int Id { get; set; } // Exclude public string Nam
CreateProduct([Bind(Include=“Name,Category”)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属性
有关这两个属性的详细信息,请访问。您可以尝试使用该属性
所以现在你们班看起来像这样-
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
}
这样,我将无法为每个操作方法指定包含/排除列表。例如,对于不同操作方法中使用的同一模型,可能有一组不同的属性要包含。我尚未对此进行测试,但通过实现IModelBinder创建自己的ModelBinder可能会帮助您找到解决方案。这样,您就可以创建一个类似于
Bind
的属性,并将其附加到您操作的参数。您找到了解决方案吗?这是特定于WCF的