Is there any difference between the Ok() method new ObjectResult()?

后端 未结 3 571
悲&欢浪女
悲&欢浪女 2021-01-01 09:21

Scenario: implementing a standard REST API / GET method on a .net core controller.

The documentation states that OkObjectResult is an ObjectResult with status 200. T

3条回答
  •  南方客
    南方客 (楼主)
    2021-01-01 09:55

    Update: Both approaches in the original question + the third approach in the accepted answer has now been superseded by simply returning the object directly:

     return myResult
    

    Relevant example and explanation from the current tutorial page:

    [HttpGet("{id}")]
    public async Task> GetTodoItem(long id)
    {
        var todoItem = await _context.TodoItems.FindAsync(id);    
        if (todoItem == null)
        {
            return NotFound();
        }    
        return todoItem;
    }
    

    The return type of the GetTodoItems and GetTodoItem methods is ActionResult< T > type. ASP.NET Core automatically serializes the object to JSON and writes the JSON into the body of the response message. The response code for this return type is 200, assuming there are no unhandled exceptions. Unhandled exceptions are translated into 5xx errors.

提交回复
热议问题