using System.Web.Http.Cors;
using System.Web.Routing;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
namespace ExceptionLogging.Controllers
[EnableCors("*.*", "*.*", "*.*")]
public class HomeController : Controller
private LoggingContext loggingContext = new LoggingContext();
public ActionResult Index()
var logs = loggingContext.ExceptionLogs.ToList();
public ActionResult AddUser()
public ActionResult AddUser(UserDetail userDetail)
if (userDetail.UserName == null)
throw new Exception("User Name cannot be empty");
loggingContext.UserDetails.Add(userDetail);
loggingContext.SaveChanges();
public class LogExceptionAttribute : FilterAttribute, IExceptionFilter
public void OnException(System.Web.Mvc.ExceptionContext filterContext)
if (!filterContext.ExceptionHandled)
var exceptionLog = new ExceptionLog()
ControllerName = filterContext.RouteData.Values["controller"].ToString(),
ActionName = filterContext.RouteData.Values["action"].ToString(),
ExceptionMessage = filterContext.Exception.Message,
StackTrace = filterContext.Exception.StackTrace,
var ctx = new LoggingContext();
ctx.ExceptionLogs.Add(exceptionLog);
filterContext.ExceptionHandled = true;
filterContext.Result = new RedirectToRouteResult(
{ "controller", "Home" },
public partial class LoggingContext : DbContext
: base("name=LoggingContext")
protected override void OnModelCreating(DbModelBuilder modelBuilder)
throw new UnintentionalCodeFirstException();
public virtual DbSet<ExceptionLog> ExceptionLogs { get; set; }
public virtual DbSet<UserDetail> UserDetails { get; set; }