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
}
};
}
}
}