webapi接口统一返回请求时间:

public class BaseController : ControllerBase
{
       protected ReturnResult<T> Result<T>(Func<ReturnResult<T>> fun)
        {
            ReturnResult<T> result = null;
            var stopWatch = new Stopwatch();
            stopWatch.Start();
            try
            {
                result = fun();
            }
            catch (Exception ex)
            {
                result = new ReturnResult<T>();
                result.Code = 500;
                result.Msg = ex.Message;                
            }
            finally
            {
                stopWatch.Stop();
                var time = stopWatch.ElapsedMilliseconds;
                result.QueryTime = time;
            }
            return result;
        }
}
ReturnResult类:
 public class ReturnResult<T>
 {     /// <summary>
        /// 状态  1成功  0或其他 失败
        /// </summary>
        public int Code { get; set; }
        /// <summary>
        /// 消息
        /// </summary>
        public string Msg { get; set; }
        /// <summary>
        /// 请求时间
        /// </summary>
        public long QueryTime { get; set; }
        /// <summary>
        /// 数据
        /// </summary>
        public T Data { get; set; }
 }

调用:

public class UserController : BaseController
{
    IUserServices _userServices;      
    public UserController(IUserServices userServices)
    {
       _userServices = userServices;
    }

   [HttpGet]
   public ReturnResult<List<string>> GetList(int length)
   {          
     return Result(() => _userServices.GetList(length));
   }
}

返回结果:

webapi接口统一返回请求时间

 

相关文章:

  • 2021-06-04
  • 2022-12-23
  • 2022-02-03
  • 2021-10-21
  • 2021-11-15
  • 2021-12-10
猜你喜欢
  • 2021-10-11
  • 2021-11-11
  • 2021-06-07
  • 2022-12-23
  • 2021-09-04
  • 2022-12-23
  • 2021-10-11
相关资源
相似解决方案