No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

BaseApi.cs 11 KiB

hace 4 años
hace 4 años
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. using Learun.Application.Base.SystemModule;
  2. using Learun.Loger;
  3. using Learun.Util;
  4. using Learun.Util.Operat;
  5. using Nancy;
  6. using Nancy.ModelBinding;
  7. using System;
  8. namespace Learun.Application.WebApi
  9. {
  10. /// <summary>
  11. /// 版 本 Learun-ADMS V7.0.0 数字化智慧校园
  12. /// Copyright (c) 2013-2018 北京泉江科技有限公司
  13. /// 创建人:数字化智慧校园-框架开发组
  14. /// 日 期:2017.05.12
  15. /// 描 述:Nancy-Api基础模块
  16. /// </summary>
  17. public class BaseApi : NancyModule
  18. {
  19. #region 构造函数
  20. public BaseApi()
  21. : base()
  22. {
  23. Before += BeforeRequest;
  24. OnError += OnErroe;
  25. }
  26. public BaseApi(string baseUrl)
  27. : base(baseUrl)
  28. {
  29. Before += BeforeRequest;
  30. OnError += OnErroe;
  31. }
  32. #endregion
  33. #region 获取请求数据
  34. /// <summary>
  35. /// 获取请求数据
  36. /// </summary>
  37. /// <typeparam name="T"></typeparam>
  38. /// <returns></returns>
  39. public T GetReqData<T>() where T : class
  40. {
  41. try
  42. {
  43. ReqParameter<string> req = this.Bind<ReqParameter<string>>();
  44. return req.data.ToObject<T>();
  45. }
  46. catch (Exception)
  47. {
  48. throw;
  49. }
  50. }
  51. /// <summary>
  52. /// 获取请求数据
  53. /// </summary>
  54. /// <returns></returns>
  55. public string GetReqData()
  56. {
  57. try
  58. {
  59. ReqParameter<string> req = this.Bind<ReqParameter<string>>();
  60. return req.data;
  61. }
  62. catch (Exception)
  63. {
  64. throw;
  65. }
  66. }
  67. /// <summary>
  68. /// 获取请求数据
  69. /// </summary>
  70. /// <typeparam name="T"></typeparam>
  71. /// <returns></returns>
  72. public T GetReq<T>() where T : class
  73. {
  74. try
  75. {
  76. T req = this.Bind<T>();
  77. return req;
  78. }
  79. catch (Exception)
  80. {
  81. throw;
  82. }
  83. }
  84. #endregion
  85. #region 响应接口
  86. /// <summary>
  87. /// 成功响应数据
  88. /// </summary>
  89. /// <param name="msg"></param>
  90. /// <returns></returns>
  91. public Response Success(string info)
  92. {
  93. ResParameter res = new ResParameter { code = ResponseCode.success, info = info, data = new object { } };
  94. return Response.AsText(res.ToJson()).WithContentType("application/json");
  95. }
  96. public Response Success(string info, string title, OperationType type, string keyValue, string content)
  97. {
  98. OperateLogModel operateLogModel = new OperateLogModel();
  99. operateLogModel.title = title;
  100. operateLogModel.type = type;
  101. operateLogModel.url = (string)WebHelper.GetHttpItems("currentUrl");
  102. operateLogModel.sourceObjectId = keyValue;
  103. operateLogModel.sourceContentJson = content;
  104. OperatorHelper.Instance.WriteOperateLog(operateLogModel, "Mobile");
  105. ResParameter res = new ResParameter { code = ResponseCode.success, info = info, data = new object { } };
  106. return Response.AsText(res.ToJson()).WithContentType("application/json");
  107. }
  108. /// <summary>
  109. /// 成功响应数据
  110. /// </summary>
  111. /// <typeparam name="T"></typeparam>
  112. /// <param name="res"></param>
  113. /// <returns></returns>
  114. public Response Success(object data)
  115. {
  116. ResParameter res = new ResParameter { code = ResponseCode.success, info = "响应成功", data = data };
  117. return Response.AsText(res.ToJson()).WithContentType("application/json");
  118. }
  119. /// <summary>
  120. /// 成功响应数据
  121. /// </summary>
  122. /// <typeparam name="T"></typeparam>
  123. /// <param name="res"></param>
  124. /// <returns></returns>
  125. public Response Success<T>(T data) where T : class
  126. {
  127. ResParameter res = new ResParameter { code = ResponseCode.success, info = "响应成功", data = data };
  128. return Response.AsText(res.ToJson()).WithContentType("application/json");
  129. }
  130. /// <summary>
  131. /// 成功响应数据
  132. /// </summary>
  133. /// <typeparam name="T"></typeparam>
  134. /// <param name="res"></param>
  135. /// <returns></returns>
  136. public Response SuccessString(string data)
  137. {
  138. ResParameter res = new ResParameter { code = ResponseCode.success, info = "响应成功", data = data };
  139. return Response.AsText(res.ToJson()).WithContentType("application/json");
  140. }
  141. /// <summary>
  142. /// 接口响应失败
  143. /// </summary>
  144. /// <param name="msg"></param>
  145. /// <returns></returns>
  146. public Response Fail(string info)
  147. {
  148. ResParameter res = new ResParameter { code = ResponseCode.fail, info = info, data = new object { } };
  149. return Response.AsText(res.ToJson()).WithContentType("application/json");
  150. }
  151. public Response FailNoLogin(string info)
  152. {
  153. ResParameter res = new ResParameter { code = ResponseCode.nologin, info = info, data = new object { } };
  154. return Response.AsText(res.ToJson()).WithContentType("application/json");
  155. }
  156. #endregion
  157. #region 权限验证
  158. public UserInfo userInfo;
  159. public string loginMark;
  160. public string token;
  161. /// <summary>
  162. /// 前置拦截器
  163. /// </summary>
  164. /// <param name="ctx"></param>
  165. /// <returns></returns>
  166. private Response BeforeRequest(NancyContext ctx)
  167. {
  168. string path = ctx.ResolvedRoute.Description.Path;
  169. //验证登录状态
  170. ReqParameter req = this.Bind<ReqParameter>();
  171. loginMark = req.loginMark;
  172. token = req.token;
  173. if (path == "/learun/adms/user/login" || path == "/" || path == "/bgimg" || path == "/learun/adms/user/img" || path == "/learun/adms/desktop/img"||path== "/learun/adms/user/imgfordc"||path== "/learun/adms/annexes/down" || path == "/learun/adms/StampPersonal/img" || path == "/quanjiang/sso/out" || path == "/quanjiang/sso/userstat")
  174. {// 登录接口,默认页面接口不做权限验证处理
  175. return null;
  176. }
  177. OperatorResult res = OperatorHelper.Instance.IsOnLine(req.token, req.loginMark);
  178. if (res.stateCode == -1)
  179. {
  180. return this.FailNoLogin("未找到登录信息");
  181. }
  182. if (res.stateCode == 0)
  183. {
  184. return this.FailNoLogin("登录信息已过期");
  185. }
  186. else
  187. {
  188. // 获取登录者信息
  189. userInfo = res.userInfo;
  190. }
  191. return null;
  192. }
  193. #endregion
  194. #region 异常抓取
  195. /// <summary>
  196. /// 日志对象实体
  197. /// </summary>
  198. private Log _logger;
  199. /// <summary>
  200. /// 日志操作
  201. /// </summary>
  202. public Log Logger
  203. {
  204. get { return _logger ?? (_logger = LogFactory.GetLogger(this.GetType().ToString())); }
  205. }
  206. /// <summary>
  207. /// 监听接口异常
  208. /// </summary>
  209. /// <param name="ctx">连接上下信息</param>
  210. /// <param name="ex">异常信息</param>
  211. /// <returns></returns>
  212. private Response OnErroe(NancyContext ctx, Exception ex)
  213. {
  214. try
  215. {
  216. this.WriteLog(ctx, ex);
  217. }
  218. catch (Exception)
  219. {
  220. }
  221. string msg = "提示:" + ex.Message;
  222. return Response.AsText(new ResParameter { code = ResponseCode.exception, info = msg }.ToJson()).WithContentType("application/json").WithStatusCode(HttpStatusCode.OK);
  223. }
  224. /// <summary>
  225. /// 写入日志(log4net)
  226. /// </summary>
  227. /// <param name="context">提供使用</param>
  228. private void WriteLog(NancyContext context, Exception ex)
  229. {
  230. if (context == null)
  231. return;
  232. string path = context.ResolvedRoute.Description.Path;
  233. var log = LogFactory.GetLogger("workflowapi");
  234. Exception Error = ex;
  235. LogMessage logMessage = new LogMessage();
  236. logMessage.OperationTime = DateTime.Now;
  237. logMessage.Url = path;
  238. logMessage.Class = "learunwebapi";
  239. logMessage.Ip = Net.Ip;
  240. logMessage.Host = Net.Host;
  241. logMessage.Browser = Net.Browser;
  242. if (userInfo != null)
  243. {
  244. logMessage.UserName = userInfo.account + "(" + userInfo.realName + ")";
  245. }
  246. if (Error.InnerException == null)
  247. {
  248. logMessage.ExceptionInfo = Error.Message;
  249. logMessage.ExceptionSource = Error.Source;
  250. logMessage.ExceptionRemark = Error.StackTrace;
  251. }
  252. else
  253. {
  254. logMessage.ExceptionInfo = Error.InnerException.Message;
  255. logMessage.ExceptionSource = Error.InnerException.Source;
  256. logMessage.ExceptionRemark = Error.InnerException.StackTrace;
  257. }
  258. string strMessage = new LogFormat().ExceptionFormat(logMessage);
  259. log.Error(strMessage);
  260. LogEntity logEntity = new LogEntity();
  261. logEntity.F_CategoryId = 4;
  262. logEntity.F_OperateTypeId = ((int)OperationType.Exception).ToString();
  263. logEntity.F_OperateType = EnumAttribute.GetDescription(OperationType.Exception);
  264. logEntity.F_OperateAccount = logMessage.UserName;
  265. if (userInfo != null)
  266. {
  267. logEntity.F_OperateUserId = userInfo.userId;
  268. }
  269. logEntity.F_ExecuteResult = -1;
  270. logEntity.F_ExecuteResultJson = strMessage;
  271. logEntity.F_Description = "移动端";
  272. logEntity.WriteLog();
  273. SendMail(strMessage);
  274. }
  275. /// <summary>
  276. /// 发送邮件
  277. /// </summary>
  278. /// <param name="body">消息</param>
  279. private void SendMail(string body)
  280. {
  281. bool ErrorToMail = Config.GetValue("ErrorToMail").ToBool();
  282. if (ErrorToMail == true)
  283. {
  284. string SystemName = Config.GetValue("SystemName");//系统名称
  285. string recMail = Config.GetValue("RereceiveErrorMail");//接收错误信息邮箱
  286. MailHelper.Send("receivebug@learun.cn", SystemName + " - 发生异常", body.Replace("-", ""));
  287. }
  288. }
  289. #endregion
  290. }
  291. }