FormatException int.Parse() 即使传递正确的格式字符串值

FormatException int.Parse() even when passing correct format string value

我正在尝试使用 AddSingleton DI 通过启动将 appsettings 初始化为 FileUploadSetting 对象。即使在不同 属性 中传递给 int.Parse() 方法的值只是为了访问 AllowedFileSize 的转换值是“3145728”,但它也会给出错误,如 FormatException。我做错了什么?

appsettings.json

"FileUploadSetting": {
    "AllowedExtensions": [ ".pdf", ".doc", ".docx" ],
    "StoredFilesPath": "Uploads/",
    "AllowedFileSize": "3145728‬" //in bytes

  },

Startup.cs

//FileUploadSetting
services.AddSingleton<WebApplication.Services.FileUpload.IFileUploadSetting>(Configuration.GetSection("FileUploadSetting").Get<WebApplication.Services.FileUpload.FileUploadSetting>());

FileUploadSetting.cs

public interface IFileUploadSetting
    {
        string[] AllowedExtensions { get; set; }
        string StoredFilesPath { get; set; }
        string AllowedFileSize { get; set; }
        int GetAllowedFileSize { get;}
    }
public class FileUploadSetting : IFileUploadSetting
    {
        public string[] AllowedExtensions { get; set; }
        public string StoredFilesPath { get; set; }
        public string AllowedFileSize { get; set; }

        public int GetAllowedFileSize
        {
            get
            {
                return int.Parse(AllowedFileSize);//**Error mention below even though when breakpoint is placed the value passed to it is "3145728‬"**
            }

        }
    }

错误

System.FormatException
  HResult=0x80131537
  Message=Input string was not in a correct format.
  Source=System.Private.CoreLib
  StackTrace:
   at System.Number.ThrowOverflowOrFormatException(ParsingStatus status, TypeCode type)
   at System.Number.ParseInt32(ReadOnlySpan`1 value, NumberStyles styles, NumberFormatInfo info)
   at System.Int32.Parse(String s)
   at Clanstech.Services.FileUpload.FileUploadSetting.get_GetAllowedFileSize() in C:\Users\admin\source\Workspaces\WebApplication\Services\FileUpload\FileUploadSetting.cs:line 18

Screenshot For Reference

最后(8 之后)有一个不可见的字符。

您会注意到以下计算结果为真:

AllowedFileSize[7] == '\u202c'

一种方法可以是

return int.Parse(AllowedFileSize.Trim('\u202c'));  

但这只是 "quick" 修复,您可能只想修复 json。删除整个值,包括双引号并重新键入它们。
如果您执行类似双击要编辑的值的操作,您的编辑器可能不会捕获该隐藏字符(Visual Studio 我测试时没有)。