How do set IdentityResult?
Asked Answered
S

3

5

I'm in a situation where I need to validate a new (or updating) users' email address using some more complex rules.

I thought of using the User store that goes into the user manager but where and how does the IdentityResult get constructed?

Do I just throw an exception and that's it? Or is there some extra validation mechanism?

Subcartilaginous answered 17/2, 2015 at 10:6 Comment(0)
S
13

IdentityResult takes an IEnumerable<String> in the constructor:

public IdentityResult(IEnumerable<string> errors)

These are the errors that will be passed back to the calling code.

Alternatively you can call this method:

var identityResult = IdentityResult.Failed("First error", "Second validation error");

This will be identical to the calling the constructor with list of strings.

Swamy answered 17/2, 2015 at 14:28 Comment(1)
Looks like .NET Core doesn't accept an error list in the constructor anymore. Alternativelly you can call IdentityResult.Failed(msgs.ToArray()).Chew
J
3

.NETCore has changed things. So to return a failed result where you assign your own errors you would have to create a fully qualified IdentityError instance for each error you want to pass.

Let's say for example you have the following errors and you want to returl a failed result with those errors:

var errors1 = "Your password is incorrect";
var errors2 = "Your email is not recognized";

To proceed and return a failed address for with these errors, you would do the following:

var result = IdentityResult.Failed(
   new IdentityError[] {
      new IdentityError{
         Code = "0001",
         Description = error1
      },
      new IdentityError{
         Code = "0002",
         Description = error2
      }
   }
);

Basically what's happeneing here is that the new Failed method of the IdentityResult expects params as IdentityError[]. Obviously, if you had many errors you'd create an IdentityError[] variable and then put all your errors in and then pass it to your Failed method.

Joletta answered 6/9, 2020 at 19:32 Comment(0)
K
1

Do it like this :

var errorMessage = new IdentityError
                {
                    Description = "error message"
                };

                result = 
                    IdentityResult.Failed(errorMessage);
Kata answered 19/6, 2021 at 19:6 Comment(1)
While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value.Lishalishe

© 2022 - 2024 — McMap. All rights reserved.