0

JsonResult我的一个控制器上有一个非常简单的方法:

[AjaxErrorHandler]
public JsonResult ApplyBasic(ApplyBasicModel applyBasicModel) {
    if (ModelState.IsValid) {
        return Json(1);
    } else {
        throw new InvalidModelStateException(400, "A required field was missing", ModelState);
    }
}

我在我的开发机器和 beta 机器上使用完全相同的POST 数据调用此方法,并且我得到了不同的响应和内容类型。我的开发机器返回正确的响应 ( application/json) 而我的测试机器正在返回text/html

Web.config在两种环境中完全相同。

什么可能导致这种差异?

编辑:这是我的自定义错误处理程序的代码AjaxErrorHandler

public class AjaxErrorHandler : FilterAttribute, IExceptionFilter {
    public string ErrorMessage { get; set; }
    public IEnumerable<string> ModelErrors { get; set; }

    public void OnException(ExceptionContext filterContext) {
        if (filterContext.HttpContext.Request.IsAjaxRequest()) {
            filterContext.ExceptionHandled = true;

            //If an HTTP Exception was thrown, make sure the correct HTTP code is returned.  Otherwise, default to a 500.
            if (filterContext.Exception is InvalidModelStateException) {
                var invalidModelStateException = filterContext.Exception as InvalidModelStateException;
                filterContext.HttpContext.Response.StatusCode = invalidModelStateException.GetHttpCode();
                ModelErrors = invalidModelStateException.ModelState.Values.SelectMany(e => e.Errors).Select(e => e.ErrorMessage);
            } else if (filterContext.Exception is HttpException) {
                var httpException = filterContext.Exception as HttpException;
                filterContext.HttpContext.Response.StatusCode = httpException.GetHttpCode();
            } else {
                filterContext.HttpContext.Response.StatusCode = 500;
            }

            filterContext.Result = new JsonResult {
                Data = new {
                    HTTPCode = filterContext.HttpContext.Response.StatusCode,
                    Exception = filterContext.Exception.Message,
                    Message = ErrorMessage,
                    ModelErrors = ModelErrors
                }
            };
        }
    }
}
4

1 回答 1

0

我必须在我的错误处理程序中添加一行代码:

filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;

显然 IIS 妨碍了我,并没有让我返回我自己的错误内容。通过指定此布尔值,可以正确返回 JSON 内容。

于 2013-06-10T21:25:59.980 回答