使用ASP.NET MVC和JQuery Form插件/文件上载检测IsAjaxRequest()

goo*_*oon 9 forms asp.net-mvc jquery file-upload

我正在使用JQuery Form插件在ASP.NET MVC应用程序上执行文件上载.我已经了解到,由于iframe用于文件上传(而不是XMLHttpRequest,这是不可能的),因此IsAjaxRequest的服务器端检查失败.

我已经看过一些与此问题相关的帖子,但没有遇到任何解决此问题的好方法.与我的其他应用程序一样,我希望能够同时支持启用JavaScript和禁用JavaScript的方案,这就是为什么我要检测请求是否为ajax.

我意识到使用的iframe方法在技术上不是ajax,但我试图模仿ajax效果.

欢迎大家提出意见.

zow*_*ens 11

您需要为IsAjaxRequest方法设置"X-Requested-With"标头以返回true.这是你在jquery中的表现.

$(document).ready(function() {
     jQuery.ajaxSetup({
          beforeSend: function (xhr) {
                xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
                return xhr;
          }
     });
});
Run Code Online (Sandbox Code Playgroud)


Nic*_*ski 11

从ASP.NET MVC 2开始(以及之后),有一个扩展方法Request.

if (Request.IsAjaxRequest())
{
     // was an ajax request
}
Run Code Online (Sandbox Code Playgroud)

在控制器方法上使用诸如.load()之类的jQuery方法将Request.IsAjaxRequest()返回true.


Jay*_*ay 9

我刚刚意识到我完全没有回答这个问题,所以我在这里添加到顶部,并在下面留下我的旧答案:

问题是当通过iFrame发布文件时,未设置"X-Requested-With"标头,并且您无法在Javascript中为普通表单POST设置特定请求标头.您将不得不求助于其他技巧,例如使用包含值的POST发送隐藏字段,然后更改或覆盖"IsAjaxRequest"扩展方法以检查此情况. 如何覆盖现有的扩展方法?

也许是最好的选择很可能会包括您自己的扩展方法有不同的名称,基于了与修改默认的MVC扩展方法的代码来检测你的iFrame上传帖子,然后你想到哪里去需要的任何地方使用您的扩展方法.


jQuery实际上默认将'X-Requested-With'标头设置为'XMLHttpRequest'.只要您小心地通过jQuery执行所有AJAX调用,它就非常有用.

根据您的需要,可以轻松地在动作过滤器中设置检测以在需要时使用它,或者甚至将其构建到控制器类中,如下所示:

[jQueryPartial]
public abstract class MyController : Controller
{
   public bool IsAjaxRequest { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

ActionFilterAttribute:

public class jQueryPartial : ActionFilterAttribute  
{  
    public override void OnActionExecuting(ActionExecutingContext filterContext)  
    { 
        // Verify if a XMLHttpRequest is fired.  
        // This can be done by checking the X-Requested-With  
        // HTTP header.  
        MyController myController = filterContext.Controller as MyController;
        if (myController != null)
        {
            if (filterContext.HttpContext.Request.Headers["X-Requested-With"] != null
                && filterContext.HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest")
            {
                myController.IsAjaxRequest = true;
            }
            else
            {
                myController.IsAjaxRequest = false;
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

并使用实现:

public class SomeController : MyController
{
    public ActionResult Index()
    {
          if (IsAjaxRequest)
               DoThis();
          else
               DoThat();

          return View();
    }
}
Run Code Online (Sandbox Code Playgroud)