首页 > Windows开发 > 详细

webapi接口统一返回请求时间

时间:2019-10-18 16:20:41      阅读:152      评论:0      收藏:0      [点我收藏+]

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接口统一返回请求时间

原文:https://www.cnblogs.com/hellocjr/p/11698485.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!