ActionResult<object> Returns 状态代码 200,ActionResult.Result.Value 确实包含正确的对象,但 ActionResult.Value 为 Null

ActionResult<object> Returns Status code 200, ActionResult.Result.Value does contain correct object, but ActionResult.Value is Null

我有一个 Web api 方法,它获取一个对象,将对象保存到数据库,然后 return 使用 return new OkObjectResult(MyObject) 更新数据库对象。 .. 这非常有效(对象出现在数据库、PK 集和 returned 中)。

    public async Task<ActionResult<MyObject>> AddMyObject(MyObject, CancellationToken ct)
    {
       try
       {
           ......Add to DB, update PK in MyObject etc....
           return new OkObjectResult(MyObject);
       }
       catch (Exception ex)
       {
           ......
           return new BadRequestObjectResult("Unknown error adding MyObject to database");
       }
    }

但是,当我调用此方法时,ReturnedActionResultMyObject.Value 为空

ActionResult<MyObject> ReturnedActionResultMyObject  = await AddMyObject(MyObject, ct);
ActionResult ReturnedResult = ReturnedActionResultMyObject.Result;
MyObject ReturnedValue = ReturnedActionResultMyObject.Value;

ReturnedResult.StatusCode 是 200,ReturnedResult.Value 有正确的 MyObject,调试时可见。

我确定这应该有效,我应该能够获得 returned MyObject。

您需要将 ReturnedValue 转换为 MyObjectType 为

MyObject ReturnedValue = (MyObject)((Microsoft.AspNetCore.Mvc.ObjectResult)ReturnedResult).Value;

作为

ActionResult<MyObject> ReturnedActionResultMyObject = await AddMyObject(MyObject, ct);                 
ActionResult ReturnedResult = ReturnedActionResultMyObject.Result;                   
MyObject ReturnedValue = (MyObject)((Microsoft.AspNetCore.Mvc.ObjectResult)ReturnedResult).Value;