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

问题描述

我有一个 web api 方法,它接受一个对象,将对象保存到数据库,然后使用 return new OkObjectResult(MyObject) 返回更新的数据库对象......这完美地工作(对象出现在数据库中,PK 集并返回).

    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,调试时可见。

我确定这应该可行,而且我应该能够获得返回的 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;

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...