Search code examples
.net-coreactionresulthttp-status-code-200

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


I have a web api method that takes a object, saves the object to the db and then returns the updated db object using return new OkObjectResult(MyObject)... this works perfectly (Object appears in db, PK set and 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");
       }
    }

However, when I call this method the ReturnedActionResultMyObject.Value is null

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

The ReturnedResult.StatusCode is 200 and ReturnedResult.Value has the correct MyObject, Visible when debugging.

I'm sure this should work and I should be able to get the returned MyObject.


Solution

  • You need to cast your ReturnedValue to MyObjectType as

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

    as

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