我认为以下ajax帖子:

@using (Ajax.BeginForm("UpdateEmail", new AjaxOptions
{
    HttpMethod = "POST",
    OnFailure = "showMessage(xhr.responseJSON.TypeMessage, xhr.responseJSON.Message)",
    OnSuccess = "showMessage(data.TypeMessage, data.Message); location.reload();",
    OnBegin = "$('#btnRefresh').attr('disabled', true)",
    OnComplete = "$('#btnRefresh').attr('disabled', false)",
 }))

和 Controller :
public ActionResult UpdateEmail(EditEmailDTO model)
{
        if (isValidCode)
        {
            //Code here to return a feedback json to be handle in OnSuccess callback - Working OK
            return new EmptyResult();
        }
        else
        {
            //Here is the problem in production
            Response.StatusCode = 422;
            feedback = new { Success = false, Message = MessageFeedback.InvalidCode, TypeMessage= TypeMessageFeedback.Error.ToString().ToLower() };
        }
        catch (InvalidEmailException exception){ //Code Here    }
        return Json(feedback, JsonRequestBehavior.AllowGet);
   }
}

当我在本地调试时,它可以完美运行,会触发OnFailure,并且我会在屏幕上获得反馈。但是,当我部署它时,我只在Chrome Dev Tools Console上看到服务器返回了422错误,并显示以下消息:
Uncaught TypeError: Cannot read property 'TypeMessage' of undefined

Ajax.BeginForm()中生成的脚本:
(function(xhr,status,error
 /**/) {
    showMessage(xhr.responseJSON.TypeMessage,        xhr.responseJSON.Message)
 })

使用 Response.StatusCode 错误,本地生产和调试是否有所不同?

最佳答案

好吧,我想出了解决方案。

问题是,在错误(4xx和5xx)响应代码的情况下(即使在Action方法上手动设置了),IIS也会覆盖响应。然后返回到回调的 xhr 对象是IIS发送的新对象,而不是我的Json。解决方案是在“操作”上添加以下行:

Response.TrySkipIisCustomErrors = true;

10-07 12:04
查看更多