Firefox 在 Ajax 请求重定向期间不保留自定义标头:ASP.NET MVC 解决方案 [英] Firefox does not preserve custom headers during Ajax request redirect: an ASP.NET MVC solution

查看:19
本文介绍了Firefox 在 Ajax 请求重定向期间不保留自定义标头:ASP.NET MVC 解决方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I use ajaxForm with jQuery, and there's one problem with Firefox - for some reason it does not preserve X-Requested-With custom header (which is used to detect IsAjaxRequest()). This leads to my controller action returning full view instead of partial since IsAjasxRequest() returns false after redirect.

This bug only happens in Firefox, it works fine in Chrome for example.

You can see this bug mentioned here. A pretty old post so I wonder why it still happens to me (I use Firefox 3.5.3). Anyway, here's the solution I invented - in my base controller class:

  protected override void OnActionExecuting(ActionExecutingContext filterContext)
  {
     var ajaxRequestBeforeRedirect = TempData["__isajaxrequest"] as string;
     if (ajaxRequestBeforeRedirect != null)
        Request.Headers.Add("X-Requested-With", ajaxRequestBeforeRedirect);
  }

  private bool IsRedirectResult(ActionResult result)
  {
     return result.GetType().Name.ToLower().Contains("redirect");
  }

  protected override void OnActionExecuted(ActionExecutedContext filterContext)
  {
     base.OnActionExecuted(filterContext);
     if (IsRedirectResult(filterContext.Result) && Request.Headers["X-Requested-With"] != null)
        TempData["__isajaxrequest"] = Request.Headers["X-Requested-With"];
  }

It works; however, I have two questions here:

  1. Is this bug really not fixed in Firefox or I don't understand something?
  2. Is it a good solution? Is there any better? I can't believe noone had this issue before.

UPDATE: for those who is interested in this issue, Request.Headers.Add has problems with IIS6 (or maybe IIS5, but anyway). So the correct way would be to store this "isAjaxRequest" flag in TempData/HttpContext.Items/base controller.

解决方案

Just in case somebody else stumbles on this question after wondering why their header-based dispatching fails in Firefox, this is not fixed as of 2010-10-11, tested in Firefox 3.6.10

https://bugzilla.mozilla.org/show_bug.cgi?id=553888 is the corresponding bug, and from the latest comments as of today (by Jonas, made on 2010-09-16) this issue will not be fixed in Firefox 4.

Furthermore, this bug seems to extend to standard settable headers such as Accept, meaning an Accept: application/json will disappear after a redirect and your xhr engine will very likely get an HTML response instead.

这篇关于Firefox 在 Ajax 请求重定向期间不保留自定义标头:ASP.NET MVC 解决方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆