问题描述
我有一个 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;