【问题标题】:HttpContext.Current.Request.IsAjaxRequest() error in MVC 4MVC 4 中的 HttpContext.Current.Request.IsAjaxRequest() 错误
【发布时间】:2013-01-15 18:17:38
【问题描述】:

我正在使用

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

【问题讨论】:

  • 修改问题添加代码。
  • Try new HttpRequestWrapper(System.Web.HttpContext.Current.Request).IsAjaxRequest() IsAjaxRequest() 采用与 HttpRequest 不同的 HttpRequestBase(并且不相关,因此有点混乱)。我认为包装器会解决你的问题。

标签: asp.net-mvc-4


【解决方案1】:

就我而言,我采用了静态方法(我在 IRouteConstraint 实现中)

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

如果您还没有此功能,请不要忘记include System.Web.Mvc

【讨论】:

    【解决方案2】:

    猜猜它起作用了...作为答案发布。

    试试

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

    IsAjaxRequest() 采用 HttpRequestBaseHttpRequest 不同(并且不相关,因此有点混乱)。我认为包装器会解决您的问题。

    【讨论】:

    • 请注意,HttpRequestWrapper 位于 System.Web 命名空间中,但 IsAjaxRequest() 是包含在 System.Web.Mvc 程序集中的扩展方法,因此您需要将这两个方法都包含在命名空间引用中
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-28
    • 2013-11-08
    • 1970-01-01
    • 1970-01-01
    • 2016-07-20
    相关资源
    最近更新 更多