Esc*_*ar5 10 model-binding asp.net-web-api
我试图在web api控制器中从我的Post Action中排除一个属性,是否有像[Bind(Exclude="Property")]asp.net web api 这样的东西?
这是我的模特:
public class ItemModel
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我想在Post Action中排除Id,因为它是自动生成的,但我需要在Get Action中返回它.
我知道我可以有两个模型,一个用于我的Post动作,一个用于我的Get动作,但我只想用一个模型做这个.
我倾向于映射模型,但这可以通过检查请求是否是 ShouldSerialize 方法中的 POST 来实现:
public class MyModel
{
public string MyProperty1 { get; set; }
public string MyProperty2 { get; set; }
public bool ShouldSerializeMyProperty2()
{
var request = HttpContext.Current.Request;
if (request.RequestType == "POST") return false;
return true;
}
}
Run Code Online (Sandbox Code Playgroud)
其中方法名称是以 ShouldSerialize 为前缀的属性名称。
请注意,这适用于 JSON。对于 XML,您需要将以下行添加到您的配置中:
config.Formatters.XmlFormatter.UseXmlSerializer = true;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
941 次 |
| 最近记录: |