我正在尝试通过使用AddSingleton DI的启动来初始化对FileUploadSetting对象的appsettings。即使只是为了访问AllowedFileSize的转换值而传递给int.Parse()方法的不同属性的值是“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
您的末尾(8号之后)有一个不可见的字符。
您会注意到AllowedFileSize[7] == '\u202c'
的评估结果为true。
一种方法是执行return int.Parse(AllowedFileSize.Trim('\u202c'));