I have created an Asp.Net Core MVC application. I want to handle two types of errors.
I have create two exceptions: UserFriendlyException and UserFriendlyViewException.
I have tried to create the ExceptionFilter that I need handle these two exceptions according these rules:
If is exception UserFriendlyViewException called then I want to return ViewResult with original ViewName and AddModelError and return original Model.
If is exception UserFriendlyException called then I want to redirect to Error view.
This is my ExceptionFilterAttribute:
public class ControllerExceptionFilterAttribute : ExceptionFilterAttribute
{
private readonly ITempDataDictionaryFactory _tempDataDictionaryFactory;
private readonly IModelMetadataProvider _modelMetadataProvider;
public ControllerExceptionFilterAttribute(ITempDataDictionaryFactory tempDataDictionaryFactory,
IModelMetadataProvider modelMetadataProvider)
{
_tempDataDictionaryFactory = tempDataDictionaryFactory;
_modelMetadataProvider = modelMetadataProvider;
}
public override void OnException(ExceptionContext context)
{
if (!(context.Exception is UserFriendlyException) && !(context.Exception is UserFriendlyViewException)) return;
var tempData = _tempDataDictionaryFactory.GetTempData(context.HttpContext);
//CreateNotification(NotificationHelpers.AlertType.Error, tempData, context.Exception.Message);
if (!tempData.ContainsKey(NotificationHelpers.NotificationKey)) return;
if (context.Exception is UserFriendlyViewException userFriendlyViewException)
{
context.ModelState.AddModelError(userFriendlyViewException.ErrorKey, userFriendlyViewException.Message);
}
if (context.ActionDescriptor is ControllerActionDescriptor controllerActionDescriptor)
{
//How pass here Model from context??
//If exists more views with same name but in another controller how pass correct ViewName?
var result = new ViewResult
{
ViewName = context.Exception is UserFriendlyViewException ?
controllerActionDescriptor.ActionName
: "Error",
TempData = tempData,
ViewData = new ViewDataDictionary(_modelMetadataProvider, context.ModelState)
{
{"Notifications", tempData[NotificationHelpers.NotificationKey] },
}
};
context.ExceptionHandled = true;
context.Result = result;
}
tempData.Remove(NotificationHelpers.NotificationKey);
}
}
I have two issues:
1.) How can I pass original Model from ExceptionContext to ViewResult?
2.) How return correct ViewName for UserFriendlyViewException if exists more Views with same name but in another Controller?