FormatException: Input string was not in a correct format.

lm1212 141 Reputation points
2022-07-06T06:07:53.507+00:00

I am receiving the error "FormatException: Input string was not in a correct format."
when running my code.

The issue is coming from the following lines:

int companyId = User.Identity.GetCompanyId().Value;  
  
public static int? GetCompanyId(this IIdentity identity)  
        {  
            Claim claim = ((ClaimsIdentity)identity).FindFirst("CompanyId");  
            
            return (claim != null) ? int.Parse(claim.Value) : null;  
        }  

In breakpoint mode, when the arrow hits line 7 above,
the value of claim (claim.value) is "" which is as good as null, or an empty string if I am right.

So I expect the method to return null.

After looking at similar instances of this error, there always appears to be issues in the parsing.
So I suspect I need to change the parsing type, but without further help from the error message I am taking a guess.

Can someone please tell me what is wrong here? Thank you.

Developer technologies | ASP.NET | ASP.NET Core
0 comments No comments
{count} votes

Answer accepted by question author
  1. Rena Ni - MSFT 2,066 Reputation points
    2022-07-07T03:37:00.2+00:00

    Hi @lm1212 ,

    It is impossible to convert empty string/null value to int type by using int.Parse(claim. Value) which is the reason why you get such error.

    You need change your code like below:

     return (claim != null & !string.IsNullOrEmpty(claim?.Value)) ? int.Parse(claim.Value) : null;  
    

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best Regards,
    Rena

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.