I'm trying to pass the accessed url to my error controller called ErrorController
so that I can log what page was being accessed at the time.
In my Global.asax.cs I have a method Application_Error
looking like this:
protected void Application_Error(object sender, EventArgs e)
{
var httpContext = ((MvcApplication)sender).Context;
var currentRouteData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(httpContext));
var currentController = " ";
var currentAction = " ";
if (currentRouteData != null)
{
if (currentRouteData.Values["controller"] != null && !String.IsNullOrEmpty(currentRouteData.Values["controller"].ToString()))
{
currentController = currentRouteData.Values["controller"].ToString();
}
if (currentRouteData.Values["action"] != null && !String.IsNullOrEmpty(currentRouteData.Values["action"].ToString()))
{
currentAction = currentRouteData.Values["action"].ToString();
}
}
var ex = Server.GetLastError();
var controller = new ErrorController();
var routeData = new RouteData();
var action = "Index";
if (ex is HttpException)
{
var httpEx = ex as HttpException;
switch (httpEx.GetHttpCode())
{
case 404:
action = "NotFound";
// Pass along some data about accessed page here
break;
// others if any
default:
action = "Index";
break;
}
}
httpContext.ClearError();
httpContext.Response.Clear();
httpContext.Response.StatusCode = ex is HttpException ? ((HttpException)ex).GetHttpCode() : 500;
httpContext.Response.TrySkipIisCustomErrors = true;
routeData.Values["controller"] = "Error";
routeData.Values["action"] = action;
controller.ViewData.Model = new HandleErrorInfo(ex, currentController, currentAction);
((IController)controller).Execute(new RequestContext(new HttpContextWrapper(httpContext), routeData));
}
And my ErrorController
looks like this:
public class ErrorController : BaseController
{
private readonly ILog _logger;
public ErrorController()
{
_logger = LogManager.GetLogger("CustomHandleErrorAttribute.class");
}
//
// GET: /Error/
public ActionResult Index()
{
return View();
}
public ActionResult NotFound(string error)
{
_logger.Error(error);
return View();
}
}
How should I go about populating the error parameter so I can log this to my file?