颐和api

ExceptionFilter.cs 2.0KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. using Microsoft.AspNetCore.Mvc;
  2. using Microsoft.AspNetCore.Mvc.Filters;
  3. using NLog;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Text;
  7. namespace MadRunFabric.Common
  8. {
  9. public class ExceptionFilter : ExceptionFilterAttribute
  10. {
  11. public override void OnException(ExceptionContext context)
  12. {
  13. //var log = LogManager.GetCurrentClassLogger();
  14. var log = LogManager.GetLogger(context.ActionDescriptor.AttributeRouteInfo.Template);
  15. var request = context.HttpContext.Request;
  16. var ip = request.Headers["X-Forwarded-For"];
  17. if (string.IsNullOrEmpty(ip))
  18. {
  19. ip = context.HttpContext.Connection.RemoteIpAddress.ToString();
  20. }
  21. string userinfo = string.Empty;
  22. var claims = context.HttpContext.User.Claims.GetEnumerator();
  23. while (claims.MoveNext())
  24. {
  25. if (claims.Current.Type.IndexOf("/") >= 0)
  26. {
  27. userinfo += claims.Current.Type.Substring(claims.Current.Type.LastIndexOf('/') + 1) + ":" + claims.Current.Value + ";";
  28. }
  29. }
  30. var param = string.Empty;
  31. try
  32. {
  33. if (request.Method == "GET")
  34. {
  35. param = request.Query.ToJson();
  36. }
  37. else
  38. {
  39. param = request.Form.ToJson();
  40. }
  41. }
  42. catch
  43. {
  44. param = "参数获取失败";
  45. }
  46. log.Error("IP:" + ip.ToString() + "|||UserInfo:" + userinfo + "|||ContentType:" + request.ContentType+ "|||Params:" + param + "|||Error:" + context.Exception.ToString());
  47. context.Result = new ContentResult() { Content = new AjaxResult { state = ResultTypes.error.ToString(), message = "系统异常,请稍后重试" }.ToJson() };
  48. base.OnException(context);
  49. }
  50. }
  51. }