簡體   English   中英

如何更新邏輯以檢查 SQL 查詢狀態並基於該邏輯在 c# 中返回真/假?

[英]How to update the logic to check the SQL query status and based on that return true/false in c#?

我是 C# 和 SQL 的新手。 我的端點代碼如下:

 public IActionResult EndSession([Required(ErrorMessage = "Session Id is required.")]string sessionId)
    {
        DateTime startTime = DateTime.Now;
        try
        {
            string logText = LogFormatter.Format(
                                WebUtilities.GetUser((ClaimsIdentity)HttpContext.User.Identity),
                                startTime, DateTime.Now, Privilege.ViewIMUData,
                                "End Session", "Attempting to delete user session.");
            logger.LogInfo(logText);

           EndUserSession(sessionId);

            logText = LogFormatter.Format(
                                WebUtilities.GetUser((ClaimsIdentity)HttpContext.User.Identity),
                                startTime, DateTime.Now, Privilege.ViewIMUData,
                                "End Session", "Successfully deleted user session.");
            logger.LogInfo(logText);

            return Ok(true);
        }
        catch (Exception ex)
        {
            string logText = LogFormatter.Format(
                                WebUtilities.GetUser((ClaimsIdentity)HttpContext.User.Identity),
                                startTime, DateTime.Now, Privilege.ViewIMUData,
                                "End Session", ex.ToString());

            logger.LogError(logText, ex);

            return StatusCode(Constants.InternalServerErrorCode, "Failed! Unable to delete user session. Please check logs for more details.");
        }
    }

我的數據訪問層代碼如下:

public void EndUserSession(string sessionId)
    {
        using (SqlConnection connection = new SqlConnection(DataSourceHelper.ConnectionString))
        {
            try
            {
                using (SqlCommand command = new SqlCommand("EndUserSession", connection))
                {
                    command.CommandType = CommandType.StoredProcedure;
                    command.CommandTimeout = Constants.SQL_COMMAND_TIMEOUT;

                    command.Parameters.AddWithValue("@SessionId", sessionId);
                    command.Parameters.AddWithValue("@SessionEndTime", DateTime.Now);

                    connection.Open();
                    command.ExecuteNonQuery();                    

                }
            }
            catch (Exception)
            {
                throw;
            }
        }
    }

存儲過程:

IF OBJECT_ID('[dbo].[EndUserSession]') IS NOT NULL
DROP PROCEDURE [dbo].[EndUserSession]
GO
CREATE PROCEDURE [dbo].[EndUserSession]
@SessionId nvarchar(36),
@SessionEndTime datetime
WITH ENCRYPTION
AS
BEGIN
UPDATE [dbo].[USER_SESSION] 
SET SESSION_END_DATETIME = @SessionEndTime
WHERE USER_SESSION_IID = @SessionId
END
GO

當數據庫中不存在給定的 sessionId 時,應用程序停止並立即捕獲錯誤並從端點拋出一個 500 內部服務器錯誤代碼,我稱之為 function。

What I want to do is update the logic so that you check the SQL query status and based on that return true/false from the EndUserSession function and based on that you log if there is a failure or if the session Id is not found in the User_Session 表。 實現這一目標的最佳方法是什么?

ExecuteNonQuery() 返回受 INSERT、UPDATE 或 DELETE 語句影響的行數。 所以我改變了函數以返回 bool 並在我的數據訪問中添加了這個邏輯:

int a = command.ExecuteNonQuery();

                    if (a == 0)
                    {
                        return false;
                    }
                    else
                    {
                        return true;
                    }

在我的端點中,我添加了一個 if 語句,如果 function 返回 true,它將返回 200,如果返回 false,則返回 400 錯誤請求日志記錄,即找不到 sessionId,因此沒有更新。 情況如下:

var testSession = EndUserSession(sessionId);

            if(testSession == true) 
            {
                logText = LogFormatter.Format(
                                WebUtilities.GetUser((ClaimsIdentity)HttpContext.User.Identity),
                                startTime, DateTime.Now, Privilege.ViewIMUData,
                                "End Session", "Successfully deleted user session.");
                logger.LogInfo(logText);

                return Ok(true);
            }
            else
            {
                logText = LogFormatter.Format(
                                WebUtilities.GetUser((ClaimsIdentity)HttpContext.User.Identity),
                                startTime, DateTime.Now, Privilege.ViewIMUData,
                                "End Session", "SessionId not found, please try again.");
                logger.LogInfo(logText);

                return BadRequest(false);
            }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM