我是ASP.NET Core的初学者,只是有关ObjectResult的一个问题。我看到了这样的代码:
public override void OnException(ExceptionContext context)
{
var myerror = new
{
Success = false,
Errors = new [] { context.Exception.Message }
};
context.Result = new ObjectResult(myerror)
{
StatusCode = 500
};
context.ExceptionHandled = true;
...
}
我的问题是:
1-对象“ myerror”的属性“ Errors”匿名类型是使用异常消息创建响应正文吗?
var myerror = new
{
mySuccess = false,
myErrors = new [] { context.Exception.Message }
};
可以吗?
context.ExceptionHandled = true;
的目的是什么?该书说,将异常标记为已处理,以防止其从MvcMiddleware中传播出去。但是为什么需要阻止它传播呢?答案 0 :(得分:1)
1)是。
2)是的,可以。您可以创建任何所需结构的对象,而不仅仅是匿名对象。
public class ErrorModel
{
public string Error { get; set; }
public int Id { get; set; }
public List<int> Values { get; set; }
}
//filter
var error = new ErrorModel
{
Error = context.Exception.Message,
Id = 1,
Values = new List<int> { 1, 2, 3 }
};
context.Result = new ObjectResult(error)
{
StatusCode = 500
};
3)应用程序中可能有多个异常过滤器,如果在处理异常时未将ExceptionHandled
设置为true
,则每个过滤器都会被调用并Result
被覆盖。此属性的目的是指示某些过滤器能够应对异常,而无需运行其他异常过滤器。当筛选器只能处理某些类型的异常时,这在方案中很有用。
//handles only exceptions caused by dividing by zero
public class DivideByZeroExceptionFilterAttribute : Attribute, IExceptionFilter
{
public void OnException(ExceptionContext context)
{
//chech if this is divide by zero exception
if (!(context.Exception is DivideByZeroException))
return;
var myerror = new
{
result = false,
message = "Division by zero went wrong"
};
context.Result = new ObjectResult(myerror)
{
StatusCode = 500
};
//set "handled" to true since exception is already property handled
//and there is no need to run other filters
context.ExceptionHandled = true;
}
}