【问题标题】:Mask string in ViewModel C#ViewModel C#中的掩码字符串
【发布时间】:2017-11-04 22:19:51
【问题描述】:

我有一个视图可以提取数据库中所有内容的列表,并且效果很好。然而,有一点信息我必须屏蔽,无论我尝试什么,我似乎都无法屏蔽它。

我想用 5 * 屏蔽它(不管字符串有多长)并显示最后 4 位数字。

你知道用我所拥有的最好的方法吗?

字符串示例:"SD46346" && "ADFF3342422" && "56-AS4566S"

控制器

    vm.Accounts = accounts
        .Select(s => new AdminViewModel.Account
        {
            Id= (s._ID.Length > 40 ? Encryptor.Decrypt(s._ID) : s._ID),
        }).ToList();
    return View(vm);

视图模型

public List<Account> Accounts { get; set;}

public class Account
{
    public string Id { get; set; }
}

我尝试过的事情:“/xxxxx”应用程序中的服务器错误。 StartIndex 不能小于零。参数名称:startIndex –

public string DisplayID
{
    get
    {
        return string.Format("*****{0}", Id.Substring(Id.Length - 4));
    }
} 

更新

这不是我的代码,而是数据库中丢失的旧数据,只有 2 个字符。

【问题讨论】:

  • 发布字符串示例。可能可以使用正则表达式。
  • 好的,我现在就这样做
  • 带有负索引的子字符串只会抓取最后 n 个字符 - 您不需要字符串的长度。

标签: c# string viewmodel string-concatenation data-masking


【解决方案1】:

对于您的要求,这可能有点矫枉过正。但这里有一个快速的扩展方法可以做到这一点。

默认使用 x 作为掩码字符,但可以使用可选字符进行更改

查看模型

string ID {get;set;}

string DisplayID 
{
    get
    {
        ID.MaskAllButLast(4,'*');
    }
}

扩展方法

   public static class Masking
{
    public static string MaskAllButLast(this string input, int charsToDisplay, char maskingChar = 'x')
    {
        int charsToMask = input.Length - charsToDisplay;
        return charsToMask > 0 ? $"{new string(maskingChar, charsToMask)}{input.Substring(charsToMask)}" : input;
    }
}

这应该不会出错,并且对于短 ID 不会出错。它还将完全显示一个简短的 ID,因此需要权衡。

【讨论】:

    【解决方案2】:

    如果您只是简单地替换显示,您还可以添加一个用于显示目的的额外属性。

    string ID {get;set;}
    
    string DisplayID 
    {
        get
        {
            return string.Format("*****{0}", ID.substring(ID.Length - 4))
        }
    }
    

    【讨论】:

    • “/xxxxx”应用程序中的服务器错误。 StartIndex 不能小于零。参数名称:startIndex
    • 总是很好地检查字符串长度是否超过您想要的。看起来你的字符串长度比 4 短。
    【解决方案3】:

    不确定我是否理解字符串(双引号和 & 号),但您应该能够根据需要修改代码。

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Text.RegularExpressions;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                string input = "SD46346\" && \"ADFF3342422\" && \"56-AS4566S";
                string pattern = @"\d{4}";  //exactly four digits in a row
                Match match = Regex.Match(input, pattern, RegexOptions.RightToLeft);
    
                string output = match.Value;
            }
        }
    }
    

    【讨论】:

    • 如何将输出值拉到我的视图中?
    • 您需要一个 Account 类的实例。
    猜你喜欢
    • 2013-08-29
    • 1970-01-01
    • 1970-01-01
    • 2022-01-19
    • 2015-02-23
    • 2020-07-08
    • 1970-01-01
    • 1970-01-01
    • 2020-04-11
    相关资源
    最近更新 更多