【问题标题】:How come ajax error doesn't trigger in my MVC project?为什么我的 MVC 项目中不会触发 ajax 错误?
【发布时间】:2014-12-18 12:42:16
【问题描述】:

所以我的视图中有一个表,并在以下脚本的帮助下将 ajax 数据发送到更新我的数据库的控制器:

$('.save-table').on('click', function () {
                var tr = $(this).parents('tr:first');
                var PredefName = tr.find("#PredefName").val();
                var PredefDescription = tr.find("#PredefDescription").val();
                var PredefID = tr.find("#PredefID").html();
                tr.find("#lblPredefName").text(PredefName);
                tr.find("#lblPredefDescription").text(PredefDescription);
                tr.find('.edit-mode, .display-mode').toggle();

                $.ajax({
                    url: '/PredefinedViews/Update/',
                    data: JSON.stringify({ pID: PredefID, pName: PredefName, pDescript: PredefDescription }),
                    type: 'POST',
                    contentType: 'application/json; charset=utf-8',
                    error: function (event, jqxhr, settings, exception) {
                        alert("something went wrong")
                        if (jqxhr.status == 401) {
                            alert("session expired!");
                        }
                    },
                    success: function (event, jqxhr, settings, exception) {
                        alert("database updated!");
                    }
                });
            });

所以我有一个会话需要 5 分钟短,我成功设置,我需要通知用户会话已过期 但错误消息在会话过期后永远不会触发!但是,即使没有任何内容保存到数据库中,它也会总是触发成功消息。 所以我的问题是,如何触发 ajax 错误?

EDIT1这是我控制器中的方法:

        [HttpPost]
    [ValidateInput(false)]
    public ActionResult Update(int pID, string pName, string pDescript)
    {
        using (PanSenseEntities context = new PanSenseEntities())
        {
            tblPredefineView existingPredefineView = context.tblPredefineViews.Find(pID);
            existingPredefineView.Name = pName;

            existingPredefineView.Description = pDescript;
            context.SaveChanges();
        }
        return Json(JsonRequestBehavior.AllowGet);
    }

EDIT2 我刚刚意识到,如果会话到期,它甚至不会到达控制器!我现在被难住了……

【问题讨论】:

  • 你能在服务器端分享你的操作代码吗?
  • 需要抛出异常或者返回Http错误

标签: jquery ajax asp.net-mvc


【解决方案1】:

Here 是一个类似的问题

来自那里的代码,@Darin Dimitrov 建议创建自定义授权属性并处理未经授权的请求:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class MyAuthorizeAttribute : AuthorizeAttribute
{
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        if (filterContext.HttpContext.Request.IsAjaxRequest())
        {
            filterContext.Result = new JsonResult
            {
                Data = new 
                { 
                    // put whatever data you want which will be sent
                    // to the client
                    message = "sorry, but you were logged out" 
                },
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };
        }
        else
        {
            base.HandleUnauthorizedRequest(filterContext);
        }
    }
}

【讨论】:

    【解决方案2】:

    在服务器端,检查会话是否过期,如果过期则抛出错误,状态码为 401,如下所示。

    throw new HttpException(401, "Unauthorized access");
    

    【讨论】:

    • 那么我应该把你建议的代码放在哪里?在ajax错误中?
    • 在执行代码中显示的任何数据库操作之前,在更新操作方法中。
    【解决方案3】:

    将您的服务器代码写入try-catch 块,并将throw 异常写入block。它肯定会触发ajax错误。请注意,当服务器的响应与您期望的不同时,将执行错误回调。只要服务器响应正确,就不会触发ajax-error。

    【讨论】:

      【解决方案4】:

      您需要检查会话,例如:

      [HttpPost]
      [ValidateInput(false)]
      public ActionResult Update(int pID, string pName, string pDescript)
      {
          if(!HttpContext.Current.User.Identity.IsAuthenticated)
          {
             throw new HttpException(401, "Unauthorized access");
          }
      
          using (PanSenseEntities context = new PanSenseEntities())
          {
              tblPredefineView existingPredefineView = context.tblPredefineViews.Find(pID);
              existingPredefineView.Name = pName;
      
              existingPredefineView.Description = pDescript;
              context.SaveChanges();
          }
          return Json(JsonRequestBehavior.AllowGet);
      }
      

      在这里,我检查会话:

      HttpContext.Current.User.Identity.IsAuthenticated
      

      然后,如果 HttpContext.Current.User.Identity.IsAuthenticated == false,您的请求中的错误块将被执行。

      【讨论】:

      • 问题是如果会话过期,断点甚至不会命中控制器。只有在会话存在时才会到达那里
      猜你喜欢
      • 2023-04-05
      • 1970-01-01
      • 2018-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-08
      • 2014-07-01
      • 1970-01-01
      相关资源
      最近更新 更多