> GetPTHeading(int" /> > GetPTHeading(int" /> > GetPTHeading(int"/>

ASP.NET Core 5 Web API for CRUD return value is too complicated for the controller to return

152 Views Asked by At

In my ASP.NET Core 5 Web API controller, I have this code:

[HttpGet("GetByUID/{uid:int}")]
public async Task<ActionResult<PTHeading>> GetPTHeading(int uid) 
{
    APIEntityResponse<PTHeading> getResponse = new();

    var getResult = await _controller.GetByValue("UID_PTHEADING", uid.ToString());

    if (getResult is null) 
    {
        return StatusCode(StatusCodes.Status500InternalServerError,
            $"Error retrieving {m_sControllerName} data from the database.");
    } 
    else 
    {
        return Ok(getResult.Result);
    }
}   

That yields the following result in SWAGGER:

{
  "value": {
    "isSuccess": true,
    "errorMessages": [],
    "data": {
      "uiD_PTHEADING": 14,
      "uiD_CUSTOMER": 17,
      "txT_PTHEADING_NAME": "Exterior",
      "booL_IS_ACTIVE": true,
      "inT_SORT_ORDER": 1
    }
  },
  "formatters": [],
  "contentTypes": [],
  "declaredType": null,
  "statusCode": 200
}

This is not what I need to be returned. I need only this section to be returned...

{
  "isSuccess": true,
  "errorMessages": [],
  "data": {
     "uiD_PTHEADING": 14,
     "uiD_CUSTOMER": 17,
     "txT_PTHEADING_NAME": "Exterior",
     "booL_IS_ACTIVE": true,
     "inT_SORT_ORDER": 1
   }
}

The getResult.Result value is shown here:

enter image description here

I don't know how to get this as a return value.

Any comments, questions or solutions are welcome. Thanks...John

1

There are 1 best solutions below

1
Yong Shun On BEST ANSWER

Based on your current code, the return Ok(getResult.Result); will treat the value of getResult.Result (OkObjectResult) as the response body.

You can return the response body with getResult.Result.Value. Note that you should check the status code first and control the value/action result to be returned.

else 
{
    if (getResult.Result.StatusCode == HttpStatusCodes.Status200OK)
        return Ok(getResult.Result.Value);
    else
        return StatusCode(StatusCodes.Status500InternalServerError,
            $"Error retrieving {m_sControllerName} data from the database."); // Custom handling when status code is not 200
}

Or you can just return the getResult directly.

else 
{
    return getResult as ActionResult<PTHeading>;
}