【问题标题】:Allow class properties to be null in WebAPI 2 post methods在 WebAPI 2 发布方法中允许类属性为空
【发布时间】:2015-08-03 14:49:02
【问题描述】:

我正在使用两个 POCO 类:

public class GearModel
{
    public long Id { get; set; }
    public Int16 LocationNumber { get; set; }
    public string HooksPerRod { get; set; }
    public string TerminalWeightBait { get; set; }
    public string TerminalWeight { get; set; }
    public FlyModel Shrimps { get; set; }
    public FlyModel Worms { get; set; }
    public FlyModel Cocahoes { get; set; }
    public FlyModel Scampi { get; set; }
}

public class FlyModel
{
    public double? Number { get; set; }
    public string Color { get; set; }
}

当我尝试发布到我的 API 控制器(定义如下)时,它抱怨 Null value for non-nullable member. Member: 'Worms'.,当使用此 cURL 命令发布到它时(我知道所有 cURL 参数都不是问题,如果我包含所有 @ 987654323@ 属性有效)。

不工作


curl -X POST -v -H "Content-Type: application/json" --data-ascii "{Assn:102,LocationNumber:1,HooksPerRod:3,TerminalWeightBait:'None',TerminalWeight:'18oz',Shrimps:{Number:0.0,Color:'Pink'}}" <Url Here>

工作


curl -X POST -v -H "Content-Type: application/json" --data-ascii "{Assn:102,LocationNumber:1,HooksPerRod:3,TerminalWeightBait:'None',TerminalWeight:'18oz',Shrimps:{Number:0.0,Color:'Pink'},Worms:{},Cocahoes:{},Scampi:{}}" <Url Here>

所以我的问题是,我如何让 FlyModel 属性(虾、蠕虫等)完全排除在 JSON 之外,就像在不工作的 cURL 命令中一样?

齿轮控制器


public class GearController : ApiController
{
    // POST: api/Gear
    [ResponseType(typeof(GearModel))]
    public async Task<IHttpActionResult> PostGearModel(GearModel gearModel)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        db.Gear.Add(gearModel);
        await db.SaveChangesAsync();

        return CreatedAtRoute("DefaultApi", new { id = gearModel.Assn }, gearModel);
    }
}

【问题讨论】:

  • 这有点奇怪,我一直在 WebAPI 中这样做,并且不记得必须配置任何东西,因为这是默认行为。我去看看。

标签: c# json asp.net-web-api2


【解决方案1】:

我假设您指的是db.SaveChangesAsync(); 之后的错误,Entity FrameworkWeb Api 在这里没有任何改变。发生错误是因为EF 不允许复杂类型为空,这意味着您需要在保存之前实例化每个复杂类型Shrimps, Worms...

您可以在以下位置阅读有关此约定的更多信息:Complex Types of Nullable ValuesComplex Types Nullability Convention

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-25
    • 2014-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多