I have default template of MVC4 project and following subscription for UnhandledException event in my Global.asax:
[SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlAppDomain)]
protected void Application_Start()
{
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
}
void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
Debugger.Break();
// Some logging code here
}
In my HomeController Index action I simply write:
throw new Exception("Test exception"):
Console application with such subscription works fine. But in MVC project handler call never occurs.
What is wrong with MVC?
UnhandledException callback is not called because when action raise exception its handled by MVC framework and AppDomain doesn't have unhandled exception so its not candidate to be unloaded and it can handle next request.
The shortest way to log exception:
protected void Application_Error(object sender, EventArgs args)
{
Debugger.Break();
Exception error = ((HttpApplication)sender).Context.Server.GetLastError();
// Some logging code here
}
Related
I am doing ajax call to asp.net mvc action(it is name SearchResults action)
In SearchResults action I set a session
context.Session["FlightSearchRequest"] = flightSearchRequest;
and then Redirect To another Action
return RedirectToAction("GetAvailableFlights");
In GetAvailableFlights action I want to access session
return context.Session["FlightSearchRequest"] as FlightSearchRequest;
But it is null
I think my session lost but why?I want to debug this
I added
protected void Session_End(object sender, System.EventArgs e)
{
}
to global.asax but it is not fired...When my session get null I want catch this what should I do ?
I am working with asp.net mvc output caching and have ran in to an issue.
I am overriding the GetVaryByCustomString method in the global asax with a customer implementation of building up the the custom string. Building up on this string is based on data that is inserted in to the httpcontext in another httpmodule.
The issue I have is that the OutputCacheModule gets fired before the values are put in to httpcontext - this is done in another httpmodule.
Is there any way I can fire a different httpmodule - before the outputcache module executes?
Or is there another work around for my situation.
Try ordering the events in the order they are executed by the .net pipeline (http://msdn.microsoft.com/en-us/library/ff649096.aspx).
For example, you can use the BeginRequest event, that is first event to be raised:
public class MyModule : IHttpModule
{
public void Init(HttpApplication context)
{
context.BeginRequest += context_BeginRequest;
}
void context_BeginRequest(object sender, EventArgs e)
{
var application = (HttpApplication)sender;
var context = application.Context;
// do something
}
public void Dispose()
{
}
}
I am working on a website which is API based, client side is being developed in .Net MVC. For exception handling, I am using
public void Application_Error(object sender, EventArgs e)
{
string action = "Index";
Exception exception = Server.GetLastError();
Response.Clear();
HttpException httpException = exception as HttpException;
if (httpException != null)
{
switch (httpException.GetHttpCode())
{
case 404:
// page not found
action = "Error404";
break;
default:
action = "Index";
break;
}
// clear error on server
Server.ClearError();
}
Response.Redirect(String.Format("/error/{0}", action));
}
so for any exception thrown by try catch from Controller, the page redirects to error page.
Now I want that when session is expired it should redirect to Login page, How can I do that?
Right now what is happening is, after session expires, when I try to access the session value, it throws exception "object reference not set to an instance of object." then it redirects to the default error page.
I don't think you're going to be able to do this from inside a generic exception handler because - as you said - missing session variables simply throw a NullReferenceException. Perform a null check on the session variable from your controller:
Public ActionResult MyAction ()
{
if (Session["myVariable"] == null)
{
RedirectToAction("SessionTimeOut", "Error");
}
...
}
If you have session variables that should always exist unless the session has expired, you could try overriding the OnActionExecuting method for your controller and performing your null check in there. To do this for multiple controllers, define a BaseController, override its OnActionExecuting method and then inherit this in your other controllers.
As asked here.
I want to know if it is possible to get the YSOD's HTML Rendering for exceptions to be sent by mail WITHOUT the use of ELMAH? I am handling the errors and showing a custom error page to the user. I am also sending the exception general information throught mail, however I really would like to know if I can wrap them into the real built-in YSOD engine of ASP.NET and keep the HTML formatting.
UPDATE1:
I have my custom exceptions (DupplicatedArbsException) that returns a view with the message which i consider "Managed Exceptions". However, if it is a real error that I did not catch, it will return the Error view.
[HandleError(ExceptionType = typeof(Exception), View = "Error")]
[HandleError(ExceptionType = typeof(DuplicatedArbsException), View = "ErrorViewArbs")]
public ActionResult Create(string id, int? version)
{
//...
}
The HandleError Raises which does nothing currently.
protected override void OnException(ExceptionContext filterContext)
{
var ex = filterContext.Exception;
base.OnException(filterContext);
}
..
<customErrors mode="On" defaultRedirect="Error"/>
The exception raised in customErrors mode="off" is the YSOD from asp.net. However, when I turn customErrors mode="on" those exceptions are not wrapped in it's html equivalent but only the exception messages (no html at all).
You could handle the Application_Error event in global.asax which is triggered by the ASP.NET engine every-time an exception is not handled:
protected void Application_Error(object sender, EventArgs e)
{
var app = (HttpApplication)sender;
var context = app.Context;
// get the exception that was unhandled
Exception ex = context.Server.GetLastError();
// TODO: log, send the exception by mail
}
I have written an HTTPModule for the redirection purpose and installed in GAC and referenced in root web.config file. It is working for Team sites very well.
I am using PreRequestHandlerExecute to see the request is page or not and calling
public void Init(HttpApplication context)
{
this.app = context;
this.app.PreRequestHandlerExecute += new EventHandler(Application_PreRequestHandlerExecute);
}
void Application_PreRequestHandlerExecute(object source, EventArgs e)
{
Page page = HttpContext.Current.CurrentHandler as Page;
if (page != null)
{
page.PreInit += new EventHandler(Perform_Redirection);
}
}
and in the Perform_Redirection method I am doing the redirection stuff.
void Perform_Redirection(object source, EventArgs e)
{
//logic goes here for redirection
}
The above code working fine for Teamsites but not for Publishing sites. The Page.PreInit is not firing for publishing sites.
Please help me to solve this problem!
I am using PreRequestHandlerExecute, because I need session object and other details otherwise I would have used BeginRequest.
I solved it by moving the redirection code into the PreRequestHandlerExecute event handler