public class ResponseOutputFormatter : TextOutputFormatter { public ResponseOutputFormatter(string contentType) { SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse(contentType)); SupportedEncodings.Add(Encoding.UTF8); SupportedEncodings.Add(Encoding.Unicode); } public override Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding) { var obj = context.Object; var response = context.HttpContext.Response; var settings = new JsonSerializerSettings { DateFormatString = "yyyy'-'MM'-'dd' 'HH':'mm':'ss", ContractResolver = new CamelCasePropertyNamesContractResolver(), }; // 这里我需要判断下当前请求的filters里是否包含NoOutputFormat,
// 如果不包含我就返回自定义的数据结构
if (!filters.Any(a => a is NoOutputFormatAttribute)) { obj = new HttpMessage() { Status = response.StatusCode, Data = obj }; } string json = JsonConvert.SerializeObject(obj, settings); return response.WriteAsync(json); } }
action 是这样的:加了 NoOutputFormatAttribute filter: [HttpGet] [NoOutputFormat] public string Get() { try { throw new IndexOutOfRangeException("Hi, Man... 索引超出范围"); } catch (Exception e) { this.logger.LogError(e, e.StackTrace, new string[] { "附加参数1", "附加参数2" }); } return string.Empty; }
告诉我怎么做?或者有其他方法实现需求的。
代码是基于asp.net core2实现的