ViewModel C# 中的掩码字符串

Mask string in ViewModel C#

我有一个视图可以提取数据库中所有内容的列表,而且效果很好。然而,有一点信息我必须掩盖,无论我怎么努力似乎都无法掩盖它。

我想用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);

ViewModel

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 个字符的旧数据。

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

string ID {get;set;}

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

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

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;
        }
    }
}

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

它默认使用 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,因此需要权衡取舍。