I'm learning ASP.NET Core
with MVC
pattern and I didn't find anything useful related to this argument.
Actually I'm looking for a way to handle all the application errors inside a single View
. The first thing that I did was create the View
for display the error, this is the design (pretty simple though):
<h2>@(ViewBag.ErrorMessage == null ? "An error happened" : "" + @ViewBag.ErrorMessage + "")</h2>
and this is the Error
controller:
public class ErrorController : Controller
{
[HttpGet]
public IActionResult Index(string errorMessage)
{
ViewBag.ErrorMessage = errorMessage;
return View();
}
}
Essentially, I used the ViewBag
for valorize a property called ErrorMessage
which contains the parameter errorMessage
.
Let me show an example of this logic for the email confirmation:
public async Task<IActionResult> ConfirmEmail(string userId, string token)
{
if (userId == null || token == null)
{
return RedirectToAction("Index", "Error");
}
var user = await _userManager.FindByIdAsync(userId);
if (user != null)
{
if (user.EmailConfirmed)
{
return RedirectToAction("Index", "Error", new { errorMessage = "Email already confirmed" });
}
IdentityResult result;
try
{
result = await _userManager.ConfirmEmailAsync(user, token);
}
catch (InvalidOperationException ex)
{
return RedirectToAction("Index", "Error", new { errorMessage = ex.Message });
}
if (result.Succeeded)
{
//TODO: Send another email
return View("ConfirmEmail", user);
}
}
return RedirectToAction("Index", "Error", new { errorMessage = "Utser not found" });
}
Now, I'm not an expert yet of ASP.NET Core
so I don't know if my practice is good enough for a production environment, someone could maybe propose a better way or improve my solution?