Last active
December 20, 2015 03:39
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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