'Handling Asp.net Errors C#
In my project I have a custom error solution. In the controller I do a try/catch and handle the exception with a popup instead of using the forms method. I can handle all of the errors correctly that are specified in the Model as the error, however I am unable to get a proper error coming from a AddError result. This is what I use:
System.Text.StringBuilder sb = new System.Text.StringBuilder();
And then I put return content(sb.ToString());
This will either show that it was successful or not. If there is an error I use this:
foreach (var key in this.ViewData.ModelState.Keys)
{
foreach (var err in this.ViewData.ModelState[key].Errors)
{
sb.Append(err.ErrorMessage + "<br/>");
}
}
And of course the Exception of the try/catch would be:
catch (Exception ex)
{
sb.Append("Error :" + ex.Message);
}
My question is how do I implement the AddErrors from context to this. I have tried
sb.Append(result); and sb.Append(result.Errors); I only see the actual error in my locals window under Error. I would like them to show up in the popup.
By the way this is for a registration form. The registration form normally just has AddErrors(result);
Thanks for your help.
UPDATE: Added AddErrors
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError("", error);
}
}
Solution 1:[1]
Because result is a type of IdentityResult but StringBuilder.Append might need to pass string value in that, so if we want to use StringBuilder.Append to append information that needs to convert as a string.
one way we can try to let result object deserialize as a JSON string value.
We can use JsonConvert.SerializeObject which is created by Json.NET
StringBuilder.Append(JsonConvert.SerializeObject(result.Errors));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | D-Shih |
