Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpContext.Current.Request.IsAjaxRequest() error in MVC 4

I am using

HttpContext.Current.Request.IsAjaxRequest() 

condition to check for an ajax request in global.asax in Application_Error method but I get the below error:

'System.Web.HttpRequest' does not contain a definition for 'IsAjaxRequest' and the best extension method overload 'System.Web.Mvc.AjaxRequestExtensions.IsAjaxRequest(System.Web.HttpRequestBase)' has some invalid arguments

Below is the code:

void Application_Error(object sender, EventArgs e)
    {

        Exception exception = Server.GetLastError().GetBaseException();
        HttpException httpException = exception as HttpException;

        string ErrorMessage = "";
        ErrorMessage = "Application Level Error";


        logger.Error(ErrorMessage, exception);

        if (System.Web.HttpContext.Current.Request.IsAjaxRequest()) //if its an ajax do not redirect
        {
            return;
        }
    else
    {
      Server.ClearError();
      this.Response.RedirectToRoute("Default", new { controller = "Home", action = "Error" });
    }
  }
like image 239
desiguy Avatar asked Jan 31 '13 15:01

desiguy


2 Answers

Guess it worked... Posting as the answer.

Try

new HttpRequestWrapper(System.Web.HttpContext.Current.Request).IsAjaxRequest() 

IsAjaxRequest() takes an HttpRequestBase which is different from an HttpRequest (and not related, so it's a bit confusing). I think the wrapper will fix your problem.

like image 86
Pete Avatar answered Nov 16 '22 04:11

Pete


In my case, I resorted to using a static method (I was in an IRouteConstraint Implementation)

bool isAjax = AjaxRequestExtensions.IsAjaxRequest(httpContext.Request);

For this to work, don't forget to include System.Web.Mvc if you don't have it already.

like image 40
Bart Avatar answered Nov 16 '22 03:11

Bart