Skip to content

Instantly share code, notes, and snippets.

@objectcraftworks
Last active December 20, 2015 03:39
Show Gist options
  • Save objectcraftworks/6065646 to your computer and use it in GitHub Desktop.
Save objectcraftworks/6065646 to your computer and use it in GitHub Desktop.
ASP.NET/MVC4 HandleError Filter to keep the ViewData set by Controller for Error View & It's layouts
using System;
using System.Linq;
using System.Web.Mvc;
namespace ObjectCraftworks
{
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public class HandleErrorWithViewDataAttribute:HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
//skip if already handled
if (filterContext.ExceptionHandled == true)
return;
base.OnException(filterContext);
//skip if not handled by base
if (filterContext.ExceptionHandled == false)
return;
var result = filterContext.Result as ViewResult;
//Skip if not ViewResult
if (result == null)
return;
//Skip the keys that is already in ViewResult's ViewData
var keysToBeAdded = filterContext.Controller
.ViewData
.Where(item => !result.ViewData.ContainsKey(item.Key));
foreach (var item in keysToBeAdded)
{
result.ViewData.Add(item);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment