[英]FormatException int.Parse() even when passing correct format string value
I am trying to initialize the appsettings to FileUploadSetting object through startup using AddSingleton DI.我正在尝试使用 AddSingleton DI 通过启动将 appsettings 初始化为 FileUploadSetting 对象。 Even though the value passed to int.Parse() method in different property just to access the converted value of AllowedFileSize is "3145728" then also it gives error as FormatException.
即使在不同属性中传递给 int.Parse() 方法的值只是为了访问 AllowedFileSize 的转换值是“3145728”,但它也会给出错误为 FormatException。 What i am doing wrong ?
我做错了什么?
appsettings.json 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文件上传设置.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"**
}
}
}
Error错误
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
You have an invisible character at the end (after the 8).最后有一个隐形字符(在 8 之后)。
You'll notice that the following evaluates to true:您会注意到以下计算结果为真:
AllowedFileSize[7] == '\u202c'
One approach could be一种方法可能是
return int.Parse(AllowedFileSize.Trim('\u202c'));
But that's just a "quick" fix, and you'll likely just want to fix the json.但这只是“快速”修复,您可能只想修复 json。 Delete the whole value, including the double quotes and re-type those as well.
删除整个值,包括双引号并重新键入它们。
Your editor probably won't capture that hidden character if you do something like double click the value to edit (Visual Studio didn't when I tested this).如果您执行诸如双击要编辑的值之类的操作(Visual Studio 在我测试时没有这样做),您的编辑器可能不会捕获该隐藏字符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.