You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

316 lines
11 KiB

  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. ctx.Request.Url.Query = Learun.Util.WebHelper.Formatstr(ctx.Request.Url.Query);
  169. foreach (var p in ctx.Parameters)
  170. {
  171. if (p.ParameterType == typeof(string))
  172. {
  173. if (ctx.Parameters[p.ParameterName] != null)
  174. {
  175. ctx.Parameters[p.ParameterName] = Learun.Util.WebHelper.Formatstr(ctx.Parameters[p.ParameterName].ToString());
  176. }
  177. }
  178. }
  179. string path = ctx.ResolvedRoute.Description.Path;
  180. //验证登录状态
  181. ReqParameter req = this.Bind<ReqParameter>();
  182. loginMark = req.loginMark;
  183. token = req.token;
  184. if (path == "/learun/adms/user/login"|| path == "/learun/adms/user/loginbyIdCard" || path == "/" || path == "/bgimg" || path == "/learun/adms/user/img" || path == "/learun/adms/desktop/img"||path== "/learun/adms/user/imgfordc"||path== "/learun/adms/timetable/timeTableData"||path== "/quanjiang/sso/authorize"||path== "/learun/nologin/adms/annexes/upload"||path== "/learun/adms/annexes/wxlist" || path == "/learun/visitmanage/save" || path == "/learun/visitmanage/getweixinaccess_token")
  185. {// 登录接口,默认页面接口不做权限验证处理
  186. return null;
  187. }
  188. OperatorResult res = OperatorHelper.Instance.IsOnLine(req.token, req.loginMark);
  189. if (res.stateCode == -1)
  190. {
  191. return this.FailNoLogin("未找到登录信息");
  192. }
  193. if (res.stateCode == 0)
  194. {
  195. return this.FailNoLogin("登录信息已过期");
  196. }
  197. else
  198. {
  199. // 获取登录者信息
  200. userInfo = res.userInfo;
  201. }
  202. return null;
  203. }
  204. #endregion
  205. #region 异常抓取
  206. /// <summary>
  207. /// 日志对象实体
  208. /// </summary>
  209. private Log _logger;
  210. /// <summary>
  211. /// 日志操作
  212. /// </summary>
  213. public Log Logger
  214. {
  215. get { return _logger ?? (_logger = LogFactory.GetLogger(this.GetType().ToString())); }
  216. }
  217. /// <summary>
  218. /// 监听接口异常
  219. /// </summary>
  220. /// <param name="ctx">连接上下信息</param>
  221. /// <param name="ex">异常信息</param>
  222. /// <returns></returns>
  223. private Response OnErroe(NancyContext ctx, Exception ex)
  224. {
  225. try
  226. {
  227. this.WriteLog(ctx, ex);
  228. }
  229. catch (Exception)
  230. {
  231. }
  232. string msg = "提示:" + ex.Message;
  233. return Response.AsText(new ResParameter { code = ResponseCode.exception, info = msg }.ToJson()).WithContentType("application/json").WithStatusCode(HttpStatusCode.OK);
  234. }
  235. /// <summary>
  236. /// 写入日志(log4net)
  237. /// </summary>
  238. /// <param name="context">提供使用</param>
  239. private void WriteLog(NancyContext context, Exception ex)
  240. {
  241. if (context == null)
  242. return;
  243. string path = context.ResolvedRoute.Description.Path;
  244. var log = LogFactory.GetLogger("workflowapi");
  245. Exception Error = ex;
  246. LogMessage logMessage = new LogMessage();
  247. logMessage.OperationTime = DateTime.Now;
  248. logMessage.Url = path;
  249. logMessage.Class = "learunwebapi";
  250. logMessage.Ip = Net.Ip;
  251. logMessage.Host = Net.Host;
  252. logMessage.Browser = Net.Browser;
  253. if (userInfo != null)
  254. {
  255. logMessage.UserName = userInfo.account + "(" + userInfo.realName + ")";
  256. }
  257. if (Error.InnerException == null)
  258. {
  259. logMessage.ExceptionInfo = Error.Message;
  260. logMessage.ExceptionSource = Error.Source;
  261. logMessage.ExceptionRemark = Error.StackTrace;
  262. }
  263. else
  264. {
  265. logMessage.ExceptionInfo = Error.InnerException.Message;
  266. logMessage.ExceptionSource = Error.InnerException.Source;
  267. logMessage.ExceptionRemark = Error.InnerException.StackTrace;
  268. }
  269. string strMessage = new LogFormat().ExceptionFormat(logMessage);
  270. log.Error(strMessage);
  271. LogEntity logEntity = new LogEntity();
  272. logEntity.F_CategoryId = 4;
  273. logEntity.F_OperateTypeId = ((int)OperationType.Exception).ToString();
  274. logEntity.F_OperateType = EnumAttribute.GetDescription(OperationType.Exception);
  275. logEntity.F_OperateAccount = logMessage.UserName;
  276. if (userInfo != null)
  277. {
  278. logEntity.F_OperateUserId = userInfo.userId;
  279. }
  280. logEntity.F_ExecuteResult = -1;
  281. logEntity.F_ExecuteResultJson = strMessage;
  282. logEntity.F_Description = "移动端";
  283. logEntity.WriteLog();
  284. SendMail(strMessage);
  285. }
  286. /// <summary>
  287. /// 发送邮件
  288. /// </summary>
  289. /// <param name="body">消息</param>
  290. private void SendMail(string body)
  291. {
  292. bool ErrorToMail = Config.GetValue("ErrorToMail").ToBool();
  293. if (ErrorToMail == true)
  294. {
  295. string SystemName = Config.GetValue("SystemName");//系统名称
  296. string recMail = Config.GetValue("RereceiveErrorMail");//接收错误信息邮箱
  297. MailHelper.Send("receivebug@learun.cn", SystemName + " - 发生异常", body.Replace("-", ""));
  298. }
  299. }
  300. #endregion
  301. }
  302. }