Asp.net-Mvc-4

MVC 4 中的 HttpContext.Current.Request.IsAjaxRequest() 錯誤

  • January 3, 2017

我在用

HttpContext.Current.Request.IsAjaxRequest() 

在 Application_Error 方法中檢查 global.asax 中的 ajax 請求的條件,但我收到以下錯誤:

“System.Web.HttpRequest”不包含“IsAjaxRequest”的定義,並且最佳擴展方法重載“System.Web.Mvc.AjaxRequestExtensions.IsAjaxRequest(System.Web.HttpRequestBase)”有一些無效參數

下面是程式碼:

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" });
   }
 }

猜猜它起作用了…發佈為答案。

嘗試

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

IsAjaxRequest()接受與 anHttpRequestBase不同的 an HttpRequest(並且不相關,因此有點令人困惑)。我認為包裝器將解決您的問題。

就我而言,我採用了靜態方法(我在 IRouteConstraint 實現中)

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

為此,include System.Web.Mvc如果您還沒有它,請不要忘記。

引用自:https://stackoverflow.com/questions/14629304