我找到了解决办法here
我不得不创建一个动作过滤器来覆盖MVC
这里的默认行为是我的异常类
class ValidationException : ApplicationException
{
public JsonResult exceptionDetails;
public ValidationException(JsonResult exceptionDetails)
{
this.exceptionDetails = exceptionDetails;
}
public ValidationException(string message) : base(message) { }
public ValidationException(string message, Exception inner) : base(message, inner) { }
protected ValidationException(
System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context)
: base(info, context) { }
}
请注意,我有构造函数初始化我的JSON。这里是动作过滤器
public class HandleUIExceptionAttribute : FilterAttribute, IExceptionFilter
{
public virtual void OnException(ExceptionContext filterContext)
{
if (filterContext == null)
{
throw new ArgumentNullException("filterContext");
}
if (filterContext.Exception != null)
{
filterContext.ExceptionHandled = true;
filterContext.HttpContext.Response.Clear();
filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
filterContext.HttpContext.Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError;
filterContext.Result = ((ValidationException)filterContext.Exception).myJsonError;
}
}
现在,我有行动过滤器,我来装饰我的控制器与过滤器属性
[HandleUIException]
public JsonResult UpdateName(string objectToUpdate)
{
var response = myClient.ValidateObject(objectToUpdate);
if (response.errors.Length > 0)
throw new ValidationException(Json(response));
}
当错误被抛出的动作过滤器,它实现个IExceptionFilter被调用和我在错误回调中返回客户端上的Json。
如果读者认为“所有必要?”,答案是“否”。 - 我和@Sarath处于相同的情况,并希望返回一个HTTP错误代码和一些描述错误的JSON数据。事实证明,我可以只使用清除响应的行,IIS自定义错误将被跳过,并且状态码已被占用。我将这3行放在我的控制器的Action中,在这3行之后,我只是像往常一样返回我的JSON数据。像魅力一样工作。 – 2013-02-10 16:17:02
事实确实如此,但为了可重复使用,您可能希望按照答案的指示进行操作,而不是将相同的代码复制/过滤到每个操作中。 – Hades 2013-06-06 15:35:39
如果我设置了'StatusCode = 500',那么它会忽略我的JsonResponse,而是返回“页面无法显示,因为发生了内部服务器错误。”。不知道这是由于OWIN管道中的差异还是由于什么。 – AaronLS 2016-04-21 19:36:33