如何解决此错误
问题描述:
An exception of type System.FormatException& occurred in mscorlib.dll but was not handled in user code
ChangePasswordModel changemodel = new ChangePasswordModel()
changemodel.AdminId = Convert.ToInt32(User.Identity.Name);
答
首先,不要使用转换
,使用int.Parse
(抛出异常)或者更好的是int.TryParse
。并非所有人输入的字符串都可以解析为整数;我不知道为什么你决定User.Identity.Name
应该。无论如何,使用我提到的方法,你可以检查它并处理无法解析字符串的情况。-SA
First of all, don't useConvert
, usesint.Parse
(which throws exception) or, better,int.TryParse
. Not all strings someone enters can be parsed as integer; I have no idea why did you decide thatUser.Identity.Name
should. Anyway, with the methods I mentioned you can check it up and handle the cases when the string cannot be parsed.—SA
除非User.Identity.Name
始终只包含0到9的数字,并且具有适合Int32的总值,Convert.ToInt32
将永远失败。
鉴于它被称为名称
它可能不是一个数字。我首先看看它应该包含什么,并检查你的实际含义是什么:
UnlessUser.Identity.Name
always contains only the digits 0 to 9, and has a total value that will fit in an Int32, thenConvert.ToInt32
will always fail.
Given that it's calledName
the chances are that it isn't a number. I'd start by looking at what it should contain, and check if what you actually meant was something like:
changemodel.AdminId = Convert.ToInt32(User.Identity.Id);
或者更有可能:
Or more likely:
changemodel.AdminId = User.Identity.Id;
但是如果你必须转换它然后使用TryParse:
But if you do have to convert it then use TryParse:
if (!int.TryParse(User.Identity.Id, out changemodel.AdminId))
{
// Report or log problem
...
}
else
{
// Work with value
...