Search code examples
c#asp.net-coreasp.net-core-webapiwebapi

HTTPPUT check if update was successful


Please help. I am trying to do a put. However, even if I update a record using an ID that does not exist it still give me a "Success". How do I check if no records were updated then return BadReques()?

 [HttpPut]

    [ProducesResponseType(StatusCodes.Status404NotFound)]
    [ProducesResponseType(StatusCodes.Status200OK)]
    public async Task<ActionResult<List<CaseInformation>>> UpdateCaseInformation(UpdateCaseInformation UpdateCaseInfo)
    {
        using var connection = new SqlConnection(_config.GetConnectionString("SQlServer"));



        var caseInfo = await connection.ExecuteAsync("dbo.UpdateCaseInformationByIDSP", UpdateCaseInfo, commandType: CommandType.StoredProcedure);

        return Ok();

Solution

  • I am trying to do a put. However, even if I update a record using an ID that does not exist it still give me a "Success"

    Actually, you are getting the expected output because you are not checking the ID you are passing to update your record whether it is exist at all. Another issue within your code were, no additional code block for comparing the condition once it got failed.

    Thus, you would need to introduce an additional block to check if the Id exist only then you would move to your update statement block otherwise execution need to stopped and return your status of 404 or bad reqeust, anything you want.

    Solution:

            [HttpPut]
            [ProducesResponseType(StatusCodes.Status404NotFound)]
            [ProducesResponseType(StatusCodes.Status200OK)]
            public async Task<ActionResult<List<CaseInformation>>> UpdateCaseInformation(UpdateCaseInformation UpdateCaseInfo)
            {
                //First Check if the case exist
                var isCaseExist = _appDbContext.YourCaseTable.Where(check => check.CaseId== UpdateCaseInfo.CaseId || check.CaseCode== UpdateCaseInfo.Code).FirstOrDefault();
                if (isCaseExist == null)
                {
                    return NotFound();
                }
                // Execute Update Operation
                //using var connection = new SqlConnection(_config.GetConnectionString("SQlServer"));
    
                //var caseInfo = await connection.ExecuteAsync("dbo.UpdateCaseInformationByIDSP", UpdateCaseInfo, commandType: CommandType.StoredProcedure);
    
    
                //Return status what you want
                var updateMessage = "Case has been updated";
                return Ok(updateMessage);
            }
    

    Note: The key point is first execute a read operation like this before moving to update operation. Its the most common practice for WEB API.

    Output:

    enter image description here

    Note: In my sample I am checking using entityframework if the data exist. You can do that using SqlDataReader as per your scenario by writing simple SqlCommand. Then, you can keep your existing code.