我正在研究 ASP.Net 样板服务项目。我想发送一个自定义异常。我实施了
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public sealed class FriendlyError : ExceptionFilterAttribute, IExceptionFilter
{
private readonly HttpStatusCode StatusCode;
public FriendlyError(HttpStatusCode statusCode = HttpStatusCode.InternalServerError)
{
StatusCode = statusCode;
}
public override void OnException(ExceptionContext context)
{
if (context.Exception == null) return;
context.HttpContext.Response.StatusCode = (int)StatusCode;
context.HttpContext.Response.ContentType = "multipart/form-data;application/json";
context.Result = new JsonResult(CreateErrorResult(context.Exception), new JsonSerializerSettings
{
Formatting = Formatting.Indented,
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
ContractResolver = new CamelCasePropertyNamesContractResolver()
});
base.OnException(context);
}
}
处理异常,并将注释放在控制器端点上。但它向客户端发送 406 (Not Acceptable) 消息。