2

I am developing an application via .Net framework 4.5 and Asp.net MVC5. I try to access to Request object in Application_Error but I get "Request is not available in this context" error.

Here is my code:

protected void Application_Error(object sender, EventArgs e)
{
    var httpContext = ((MvcApplication)sender).Context;
    var req1 = httpContext.Request;

also I tried this

var req2= HttpContext.Current.Request;

while the second code is working fine in Asp.net MVC3 projects.

Any Idea?

6
  • I need this because I have some exceptions that are not thrown from any Controller Commented Mar 30, 2014 at 10:28
  • Are those errors thrown from background threads or tasks that you might have started? Commented Mar 30, 2014 at 10:29
  • @DarinDimitrov yes, I flick through some assemblies to find some interfaces and some assemblies throw exception then I wrap them into myException and rethrow them. Then I need my exception to be showon on my view, also I want a globlal exception handler since there might be other exceptions and I want to show them in my view Commented Mar 30, 2014 at 10:38
  • 1
    If the exception is thrown in a background thread what Request object do you expect to be able to retrieve? The HttpContext might have been disposed long time ago. Commented Mar 30, 2014 at 13:31
  • 1
    You can't. This doesn't make any sense. In Application_Start there's no concept of an HttpContext. You shouldn't be throwing any errors in your Application_Start. The best you could do in this case is log the error. But you cannot display anything to the user simply because at this stage there's no concept of an HttpContext. Commented Mar 30, 2014 at 14:07

1 Answer 1

2

here you are :-)

   protected void Application_Error()
        {
             HttpContext httpContext = HttpContext.Current;
                if (httpContext != null)
                {
                    RequestContext requestContext =((MvcHandler)httpContext.CurrentHandler).RequestContext;
                }
         }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.