如何在C# ASP.NET Core的会话验证代码中添加多场景检查条件并避免冗余if语句
Solution to Session Validation Logic Enhancement
Nice question! Let's start by clarifying the priority of your validation scenarios—this will help us build clean, maintainable code without messy nested if statements:
Scenario Priority (Highest to Lowest)
- User not signed in: Validate the request's session ID
- User signed in, but request session ID exists and doesn't match the claim's session ID: Validate the request's session ID
- User signed in, request session ID is empty: Validate the claim's session ID
- User signed in, request session ID matches the claim's session ID: Validate either (we'll use the claim's for consistency)
Clean Code Implementation (C# Example)
First, we can avoid redundant method calls by caching the key values upfront, then use a switch expression (available in C# 8+) to map each scenario to the correct session ID. This keeps logic flat and easy to read:
// Cache values to avoid repeated method calls var isUserSignedIn = UserPreviouslySignedIn(); var requestSessionId = GetRequestSessionId(); var claimSessionId = GetClaimSessionId(); // Use switch expression to handle all scenarios cleanly var sessionToValidate = (isUserSignedIn, requestSessionId, claimSessionId) switch { // 1. User hasn't signed in yet: use request session ID (false, _, _) => requestSessionId, // 2. User is signed in, request session ID exists and doesn't match claim: use request session ID (true, not null, var cs) when requestSessionId != cs => requestSessionId, // 3. User is signed in, request session ID is empty: use claim session ID (true, null, var cs) => cs, // 4. All other cases (signed in, request ID matches claim): use claim session ID (true, _, _) => claimSessionId, }; await ValidateUserRequest(context, sessionToValidate);
Even More Maintainable: Extract to a Helper Method
If this logic is used in multiple places, extract it to a dedicated helper method to keep your main code concise:
// Helper method encapsulates all session validation logic private string DetermineSessionToValidate() { var isUserSignedIn = UserPreviouslySignedIn(); var requestSessionId = GetRequestSessionId(); var claimSessionId = GetClaimSessionId(); return (isUserSignedIn, requestSessionId, claimSessionId) switch { (false, _, _) => requestSessionId, (true, not null, var cs) when requestSessionId != cs => requestSessionId, (true, null, var cs) => cs, (true, _, _) => claimSessionId, }; } // Main code becomes clean and focused var sessionToValidate = DetermineSessionToValidate(); await ValidateUserRequest(context, sessionToValidate);
Why This Works
- No nested
ifstatements—each scenario is a clear, separate case in the switch expression - Logic is easy to modify or extend later (just add a new case to the switch)
- Caching the values upfront avoids redundant calls to
UserPreviouslySignedIn(),GetRequestSessionId(), andGetClaimSessionId()
内容的提问来源于stack exchange,提问作者Noelia
相关产品推荐
相关产品推荐

