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)); } }
返回结果: