【问题标题】:Null checker fails C#空值检查失败 C#
【发布时间】:2022-01-16 11:19:40
【问题描述】:

我的 null 检查器失败了,这里有什么问题?

我正在尝试检查用户声明是否存在变量 sID,它只是回发模型的人员 ID

所以我添加了一个 try catch 语句来阻止它崩溃

  var sID = ViewModel_CreateNewAgent.Tbl_Brands_Staff.BranchStaffID.ToString();
  var staffIDExists = _context.AspNetUserClaims.Where(c => c.ClaimValue == sID).FirstOrDefaultAsync();

                    /// VALIDATE STAFF ID
                    var claimsExists = await _userManager.GetClaimsAsync(user);
                
                    var doesStaffIDExist ="";
                    try
                    {
                        doesStaffIDExist = staffIDExists.Result.ClaimValue ?? doesStaffIDExist;
                        //doesStaffIDExist = staffIDExists.Result.ClaimValue != null ? staffIDExists.Result.ClaimValue : doesStaffIDExist ;
                    }catch(Exception err) { }

【问题讨论】:

  • staffIDExists 可以为空,staffIDExists.Result 可以为空(不太可能),ClaimValue 也是一个字符串,所以它可以是“”,你为什么不设置一个断点并检查.. .
  • “我的空检查器”是什么意思? “失败”是什么意思?
  • 它是一个用户注册页面,用于检查 SID 是否存在,如果不存在。它返回 null,因此使代码崩溃。我想检查是否为空,然后给它分配任何内容或零。

标签: c# error-handling claims-based-identity


【解决方案1】:

不要将try-catch用于正常工作流程,尝试解决真正的问题。

这里staffIDExists 和/或staffIDExists.Result 和/或ClaimValue 可能是null。使用null conditional operator? 使您的代码安全且可读:

var staffIDExists = _context.AspNetUserClaims.Where(c => c.ClaimValue == sID).FirstOrDefaultAsync();
string doesStaffIDExist = claimsExists?.Result?.ClaimValue ?? "";

但是,该代码有意义吗? Where 检查c.ClaimValue == sID,所以doesStaffIDExist 总是""(如果没有这样的声明)或sid

我正在尝试检查该变量是否存在用户声明 身份证

好吧,那么这段代码会更简单:

return _context.AspNetUserClaims.Any(c => c.ClaimValue == sID);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-08
    相关资源
    最近更新 更多