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.

725 lines
26 KiB

3 years ago
11 months ago
3 years ago
2 years ago
11 months ago
2 years ago
11 months ago
3 years ago
11 months ago
3 years ago
11 months ago
3 years ago
2 years ago
11 months ago
3 years ago
2 years ago
11 months ago
2 years ago
3 years ago
11 months ago
3 years ago
11 months ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
11 months ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
11 months ago
3 years ago
11 months ago
9 months ago
11 months ago
3 years ago
11 months ago
3 years ago
11 months ago
3 years ago
11 months ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
11 months ago
3 years ago
11 months ago
3 years ago
11 months ago
3 years ago
3 years ago
11 months ago
3 years ago
11 months ago
3 years ago
11 months ago
3 years ago
11 months ago
3 years ago
11 months ago
3 years ago
11 months ago
3 years ago
2 years ago
3 years ago
11 months ago
2 years ago
3 years ago
11 months ago
3 years ago
11 months ago
3 years ago
11 months ago
3 years ago
11 months ago
3 years ago
11 months ago
3 years ago
11 months ago
3 years ago
11 months ago
3 years ago
11 months ago
3 years ago
11 months ago
3 years ago
11 months ago
3 years ago
11 months ago
3 years ago
3 years ago
3 years ago
11 months ago
3 years ago
2 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
2 years ago
2 years ago
2 years ago
3 years ago
11 months ago
3 years ago
11 months ago
3 years ago
11 months ago
3 years ago
2 years ago
3 years ago
  1. using Apewer.Network;
  2. using Apewer.Source;
  3. using System;
  4. using System.Net;
  5. using System.Reflection;
  6. using static Apewer.Web.ApiUtility;
  7. namespace Apewer.Web
  8. {
  9. internal class ApiProcessor
  10. {
  11. private ApiContext _context = null;
  12. internal ApiProcessor(ApiContext context) => _context = context ?? throw new ArgumentNullException(nameof(context));
  13. #region prepare
  14. /// <summary>执行处理程序,返回错误信息。</summary>
  15. public void Run()
  16. {
  17. var url = null as Uri;
  18. var method = HttpMethod.NULL;
  19. var response = null as ApiResponse;
  20. try
  21. {
  22. // 检查执行的前提条件,获取 Method 和 URL。
  23. var check = Check(ref method, ref url);
  24. if (!string.IsNullOrEmpty(check))
  25. {
  26. Logger.Internals.Error(typeof(ApiInvoker), check);
  27. return;
  28. }
  29. // 准备请求模型。
  30. var request = GetRequest(_context.Provider, _context.Options, method, url);
  31. _context.Request = request;
  32. // 准备响应模型。
  33. response = new ApiResponse();
  34. response.Random = request.Random;
  35. response.Application = request.Application;
  36. response.Function = request.Function;
  37. _context.Response = response;
  38. // 调用 API。
  39. Invoke();
  40. }
  41. catch (Exception ex)
  42. {
  43. var message = ex.Message();
  44. Logger.Internals.Error(typeof(ApiInvoker), message);
  45. }
  46. finally
  47. {
  48. // 输出。
  49. if (response != null)
  50. {
  51. try
  52. {
  53. response.Duration = Duration(_context.Beginning);
  54. Output(_context.Provider, _context.Options, response, null, method);
  55. }
  56. catch { }
  57. finally
  58. {
  59. RuntimeUtility.Dispose(response.Model);
  60. }
  61. }
  62. }
  63. }
  64. static string Duration(DateTime beginning)
  65. {
  66. var span = DateTime.Now - beginning;
  67. var ms = span.TotalMilliseconds;
  68. if (ms < 1000) return Math.Round(ms, 0).ToString() + "ms";
  69. if (ms < 10000) return Math.Round(ms / 1000, 2).ToString() + "s";
  70. if (ms < 60000) return Math.Round(ms / 1000, 1).ToString() + "s";
  71. return Math.Round(ms / 1000, 0).ToString() + "s";
  72. }
  73. string Check(ref HttpMethod method, ref Uri url)
  74. {
  75. // 服务程序检查。
  76. var check = _context.Provider.PreInvoke();
  77. if (!string.IsNullOrEmpty(check)) return check;
  78. // URL
  79. url = _context.Provider.GetUrl();
  80. if (url == null) return "URL 无效。";
  81. method = _context.Provider.GetMethod();
  82. if (method == HttpMethod.NULL) return "HTTP 方法无效。";
  83. if (method == HttpMethod.OPTIONS) return null;
  84. // favicon.ico
  85. var lowerPath = TextUtility.AssureStarts(TextUtility.Lower(url.AbsolutePath), "/");
  86. if (!_context.Options.AllowFavIcon)
  87. {
  88. if (lowerPath.StartsWith("/favicon.ico"))
  89. {
  90. Output(_context.Provider, _context.Options, null, null, null);
  91. return "已取消对 favicon.ico 的请求。";
  92. }
  93. }
  94. // robots.txt
  95. if (!_context.Options.AllowRobots)
  96. {
  97. if (lowerPath.StartsWith("/robots.txt"))
  98. {
  99. const string text = "User-agent: *\nDisallow: / \n";
  100. Output(_context.Provider, _context.Options, null, "text/plain", TextUtility.Bytes(text));
  101. return "已取消对 robots.txt 的请求。";
  102. }
  103. }
  104. return null;
  105. }
  106. // 寻找入口。
  107. void Invoke()
  108. {
  109. // 路由
  110. if (_context.Options.UseRoute)
  111. {
  112. var path = _context?.Request?.Url?.AbsolutePath;
  113. var action = _context.Entries.GetAction(path);
  114. if (action != null)
  115. {
  116. _context.ApiAction = action;
  117. Invoke(action);
  118. _context.Response.Duration = Duration(_context.Beginning);
  119. return;
  120. }
  121. }
  122. // 反射
  123. if (_context.Options.UseReflection)
  124. {
  125. var appName = _context.Request.Application;
  126. var application = _context.Entries.GetApplication(appName);
  127. Invoke(application);
  128. _context.Response.Duration = Duration(_context.Beginning);
  129. return;
  130. }
  131. // 未匹配到
  132. _context.Response.Duration = Duration(_context.Beginning);
  133. _context.Response.Model = new ApiStatusModel(404);
  134. }
  135. #endregion
  136. #region common
  137. // 创建控制器实例
  138. static ApiController CreateController(Type type, ApiRequest request, ApiResponse response, ApiOptions options)
  139. {
  140. var controller = (ApiController)Activator.CreateInstance(type);
  141. ApiUtility.SetProperties(controller, request, response, options);
  142. return controller;
  143. }
  144. static void Invoke(ApiContext context, MethodInfo method, ApiParameter[] parameters)
  145. {
  146. context.MethodInfo = method;
  147. // 调用。
  148. var parametersValue = ReadParameters(context.Request, parameters);
  149. var controller = context.Controller;
  150. var returnValue = method.Invoke(controller, parametersValue);
  151. // 程序要求停止输出。
  152. var response = context.Response;
  153. if (response.StopReturn) return;
  154. // 已经有了返回模型。
  155. if (response.Model != null) return;
  156. // 没有返回类型。
  157. var returnType = method.ReturnType;
  158. if (returnType == null) return;
  159. // 已明确字符串类型。
  160. if (returnType.Equals(typeof(string)))
  161. {
  162. var textValue = returnValue as string;
  163. var textRenderer = context.Options.TextRenderer;
  164. if (textRenderer != null)
  165. {
  166. textRenderer.Invoke(context, textValue);
  167. return;
  168. }
  169. // 默认视为提示错误
  170. if (!string.IsNullOrEmpty(textValue)) response.Error(textValue);
  171. return;
  172. }
  173. // 已明确 Exception 类型,视为提示错误。
  174. if (returnValue is Exception)
  175. {
  176. ApiUtility.Exception(response, returnValue as Exception);
  177. return;
  178. }
  179. // 已明确 Json 类型。
  180. if (returnValue is Json json)
  181. {
  182. response.Data = json;
  183. return;
  184. }
  185. // 已明确 Model 类型。
  186. if (returnValue is IApiModel model)
  187. {
  188. response.Model = model;
  189. return;
  190. }
  191. // 已明确 Result 类型。
  192. if (returnValue is IActionResult result)
  193. {
  194. response.Model = result;
  195. return;
  196. }
  197. // 类型未知,尝试 ToJson 方法。
  198. if (returnValue is IToJson toJson)
  199. {
  200. response.Data = toJson.ToJson();
  201. return;
  202. }
  203. // 未知返回类型,尝试使用默认渲染器。
  204. var defaultRenderer = context.Options.DefaultRenderer;
  205. if (defaultRenderer != null) defaultRenderer.Invoke(context, returnValue);
  206. }
  207. #endregion
  208. #region route
  209. // 执行 Action。
  210. void Invoke(ApiAction action)
  211. {
  212. var controller = null as ApiController;
  213. try
  214. {
  215. // 准备控制器。
  216. controller = CreateController(action.Type, _context.Request, _context.Response, _context.Options);
  217. // 准备参数。
  218. var parameters = action.Parameters;
  219. var values = ReadParameters(_context.Request, parameters);
  220. // 调用。
  221. _context.Controller = controller;
  222. Invoke(_context, action.MethodInfo, action.Parameters);
  223. }
  224. catch (Exception ex)
  225. {
  226. if (ex.InnerException != null) ex = ex.InnerException;
  227. ApiUtility.Exception(_context.Response, ex, _context.Options.WithException);
  228. var catcher = _context.Invoker.Catcher;
  229. if (catcher != null)
  230. {
  231. try
  232. {
  233. var apiCatch = new ApiCatch(_context, ex);
  234. catcher.Invoke(apiCatch);
  235. }
  236. catch { }
  237. }
  238. }
  239. finally
  240. {
  241. RuntimeUtility.Dispose(controller);
  242. }
  243. }
  244. #endregion
  245. #region reflection
  246. // 创建控制器。
  247. void Invoke(ApiApplication application)
  248. {
  249. var options = _context.Options;
  250. var entries = _context.Entries;
  251. var request = _context.Request;
  252. var response = _context.Response;
  253. // Application 无效,尝试默认控制器和枚举。
  254. if (application == null)
  255. {
  256. var @default = options.Default;
  257. if (@default == null)
  258. {
  259. // 没有指定默认控制器,尝试枚举。
  260. response.Status = "notfound";
  261. response.Message = "Not Found";
  262. if (options.AllowEnumerate) response.Data = Enumerate(entries.Applications, options);
  263. return;
  264. }
  265. else
  266. {
  267. // 创建默认控制器。
  268. var controller = null as ApiController;
  269. try
  270. {
  271. controller = CreateController(@default, request, response, options);
  272. Invoke(controller, application, null, options, request, response);
  273. }
  274. catch (Exception ex)
  275. {
  276. ApiUtility.Exception(response, ex.InnerException ?? ex);
  277. }
  278. finally
  279. {
  280. RuntimeUtility.Dispose(controller);
  281. }
  282. }
  283. }
  284. else
  285. {
  286. // 创建控制器时候会填充 Controller.Request 属性,可能导致 Request.Function 被篡改,所以在创建之前获取 Function。
  287. var function = application.GetFunction(request.Function);
  288. var controller = null as ApiController;
  289. try
  290. {
  291. controller = CreateController(application.Type, request, response, options);
  292. Invoke(controller, application, function, options, request, response);
  293. }
  294. catch (Exception ex)
  295. {
  296. ApiUtility.Exception(response, ex.InnerException ?? ex);
  297. }
  298. finally
  299. {
  300. RuntimeUtility.Dispose(controller);
  301. }
  302. }
  303. }
  304. // 调用 Function。
  305. void Invoke(ApiController controller, ApiApplication application, ApiFunction function, ApiOptions options, ApiRequest request, ApiResponse response)
  306. {
  307. try
  308. {
  309. // 控制器初始化。
  310. var initializer = ApiUtility.GetInitialier(controller);
  311. var match = initializer == null ? true : initializer.Invoke(controller);
  312. if (!match) return;
  313. if (application.Independent) return;
  314. if (function != null)
  315. {
  316. // 调用 API,获取返回值。
  317. _context.Controller = controller;
  318. Invoke(_context, function.Method, function.Parameters);
  319. }
  320. else
  321. {
  322. // 未匹配到 Function,尝试 Default。
  323. var @default = ApiUtility.GetDefault(controller);
  324. if (@default != null)
  325. {
  326. @default.Invoke(controller);
  327. return;
  328. }
  329. // 没有执行任何 Function,尝试枚举。
  330. response.Status = "notfound";
  331. if (application.Hidden)
  332. {
  333. response.Message = "Not Found";
  334. }
  335. else
  336. {
  337. response.Message = "Not Found";
  338. if (options.AllowEnumerate) response.Data = Enumerate(application.Functions, options);
  339. }
  340. }
  341. }
  342. catch (Exception ex)
  343. {
  344. if (ex.InnerException != null) ex = ex.InnerException;
  345. ApiUtility.Exception(_context.Response, ex, _context.Options.WithException);
  346. var catcher = _context.Invoker.Catcher;
  347. if (catcher != null)
  348. {
  349. try
  350. {
  351. var apiCatch = new ApiCatch(_context, ex);
  352. catcher.Invoke(apiCatch);
  353. }
  354. catch { }
  355. }
  356. }
  357. }
  358. #endregion
  359. #region static
  360. internal static ApiRequest GetRequest(ApiProvider provider, ApiOptions options, HttpMethod method, Uri url)
  361. {
  362. // 创建数据对象。
  363. var request = new ApiRequest();
  364. // Http Method。
  365. request.Method = method;
  366. // 基本信息。
  367. var ip = provider.GetClientIP();
  368. var headers = provider.GetHeaders() ?? new HttpHeaders();
  369. request.Headers = headers;
  370. request.IP = ip;
  371. request.Url = url;
  372. request.Referrer = provider.GetReferrer();
  373. request.Parameters = ApiUtility.Parameters(url.Query);
  374. // Headers。
  375. request.UserAgent = ApiUtility.UserAgent(headers);
  376. request.Cookies = ParseCookies(headers) ?? new CookieCollection();
  377. // 匹配 API。
  378. var application = null as string;
  379. var function = null as string;
  380. var random = null as string;
  381. var ticket = null as string;
  382. var session = null as string;
  383. var page = null as string;
  384. // 解析 POST 请求。
  385. switch (request.Method)
  386. {
  387. case HttpMethod.PATCH:
  388. case HttpMethod.POST:
  389. case HttpMethod.PUT:
  390. var preRead = provider.PreRead();
  391. if (string.IsNullOrEmpty(preRead))
  392. {
  393. var post = null as byte[];
  394. var length = 0L;
  395. var max = options.MaxRequestBody;
  396. if (max == 0) post = new byte[0];
  397. else if (max < 0) post = provider.RequestBody().Read();
  398. else
  399. {
  400. length = provider.GetContentLength();
  401. if (length <= max) post = provider.RequestBody().Read();
  402. }
  403. length = post == null ? 0 : post.Length;
  404. if (length > 1)
  405. {
  406. request.PostData = post;
  407. if (length < 104857600)
  408. {
  409. var text = TextUtility.FromBytes(post);
  410. request.PostText = text;
  411. // 尝试解析 Json,首尾必须是“{}”或“[]”。
  412. var first = post[0];
  413. var last = post[length - 1];
  414. if ((first == 123 && last == 125) || (first == 91 && last == 93))
  415. {
  416. var json = Json.From(text);
  417. if (json != null && json.IsObject)
  418. {
  419. application = json["application"];
  420. function = json["function"];
  421. random = json["random"];
  422. ticket = json["ticket"];
  423. session = json["session"];
  424. page = json["page"];
  425. var data = json.GetProperty("data");
  426. request.PostJson = json;
  427. request.Data = data ?? Json.NewObject();
  428. }
  429. }
  430. // 尝试解析 Form,需要 application/x-www-form-urlencoded
  431. var contentType = headers.GetValue("Content-Type") ?? "";
  432. if (contentType.Contains("urlencoded")) request.Form = ApiUtility.Parameters(text);
  433. }
  434. }
  435. }
  436. break;
  437. }
  438. // 解析 URL 参数。
  439. // URL 参数的优先级应高于 URL 路径,以避免反向代理产生的路径问题。
  440. var urlParameters = ApiUtility.Parameters(request.Url.Query);
  441. if (string.IsNullOrEmpty(application)) application = urlParameters.GetValue("application");
  442. if (string.IsNullOrEmpty(function)) function = urlParameters.GetValue("function");
  443. if (string.IsNullOrEmpty(random)) random = urlParameters.GetValue("random");
  444. if (string.IsNullOrEmpty(ticket)) ticket = urlParameters.GetValue("ticket");
  445. if (string.IsNullOrEmpty(session)) session = urlParameters.GetValue("session");
  446. if (string.IsNullOrEmpty(page)) page = urlParameters.GetValue("page");
  447. // 从 Cookie 中获取 Ticket。
  448. var cookies = request.Cookies;
  449. if (string.IsNullOrEmpty(ticket)) ticket = cookies.GetValue("ticket");
  450. // 最后检查 URL 路径。
  451. var paths = (request.Url.AbsolutePath ?? "").Split('/');
  452. if (string.IsNullOrEmpty(application) && paths.Length >= 2) application = TextUtility.DecodeUrl(paths[1]);
  453. if (string.IsNullOrEmpty(function) && paths.Length >= 3) function = TextUtility.DecodeUrl(paths[2]);
  454. // 修正内容。
  455. application = TextUtility.Trim(application);
  456. function = TextUtility.Trim(function);
  457. random = TextUtility.Trim(random);
  458. ticket = TextUtility.Trim(ticket);
  459. session = TextUtility.Trim(session);
  460. page = TextUtility.Trim(page);
  461. // 设置请求:回传。
  462. request.Application = application;
  463. request.Function = function;
  464. request.Random = random;
  465. // 设置请求:不回传。
  466. request.Ticket = ticket;
  467. request.Session = session;
  468. request.Page = page;
  469. return request;
  470. }
  471. static StringPairs PrepareHeaders(ApiOptions options, ApiResponse response, ApiRequest request = null)
  472. {
  473. var merged = new StringPairs();
  474. if (options != null)
  475. {
  476. // 跨域访问。
  477. if (options.WithAccessControl)
  478. {
  479. merged.Add("Access-Control-Allow-Headers", "Content-Type");
  480. merged.Add("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
  481. merged.Add("Access-Control-Allow-Origin", "*");
  482. var maxage = options.AccessControlMaxAge;
  483. if (maxage > 0) merged.Add("Access-Control-Max-Age", maxage.ToString());
  484. if (request != null && request.Headers != null)
  485. {
  486. var @private = request.Headers.GetValue("Access-Control-Request-Private-Network");
  487. if (NumberUtility.Boolean(@private)) merged.Add("Access-Control-Allow-Private-Network", "true");
  488. }
  489. }
  490. // Content-Type 检查。
  491. if (options.WithContentTypeOptions || options.Default != null)
  492. {
  493. merged.Add("X-Content-Type-Options", "nosniff");
  494. }
  495. // 用于客户端,当前页面使用 HTTPS 时,将资源升级为 HTTPS。
  496. if (options.UpgradeHttps)
  497. {
  498. merged.Add("Content-Security-Policy", "upgrade-insecure-requests");
  499. }
  500. // 包含 API 的处理时间。
  501. if (options.WithDuration && response != null)
  502. {
  503. if (response.Duration.NotEmpty()) merged.Add("Duration", response.Duration);
  504. }
  505. }
  506. if (response != null)
  507. {
  508. // Cookies。
  509. var setCookies = SetCookie(response.Cookies);
  510. if (setCookies != null)
  511. {
  512. foreach (var value in setCookies) merged.Add("Set-Cookie", value);
  513. }
  514. // 自定义头。
  515. var headers = response.Headers;
  516. if (headers != null)
  517. {
  518. foreach (var header in headers)
  519. {
  520. var key = TextUtility.Trim(header.Name);
  521. if (string.IsNullOrEmpty(key)) continue;
  522. var value = header.Value;
  523. if (string.IsNullOrEmpty(value)) continue;
  524. merged.Add(key, value);
  525. }
  526. }
  527. }
  528. return merged;
  529. }
  530. internal void Output(ApiProvider provider, ApiOptions options, ApiResponse response, string type, byte[] bytes)
  531. {
  532. var preWrite = provider.PreWrite();
  533. if (!string.IsNullOrEmpty(preWrite)) return;
  534. if (response != null)
  535. {
  536. var responsePreOutput = response.PreOutput;
  537. if (responsePreOutput != null)
  538. {
  539. var @continue = responsePreOutput.Invoke(_context);
  540. if (!@continue) return;
  541. }
  542. }
  543. var invokerPreOutput = _context.Invoker.PreOutput;
  544. if (invokerPreOutput != null)
  545. {
  546. var @continue = invokerPreOutput.Invoke(_context);
  547. if (!@continue) return;
  548. }
  549. var optionsPreOutput = _context.Options.PreOutput;
  550. if (optionsPreOutput != null)
  551. {
  552. var @continue = optionsPreOutput.Invoke(_context);
  553. if (!@continue) return;
  554. }
  555. var headers = PrepareHeaders(options, response);
  556. foreach (var header in headers) provider.SetHeader(header.Key, header.Value);
  557. provider.SetCache(0);
  558. provider.SetContentType(string.IsNullOrEmpty(type) ? "application/octet-stream" : type);
  559. var length = bytes == null ? 0 : bytes.Length;
  560. provider.SetContentLength(length);
  561. if (length > 0) provider.ResponseBody().Write(bytes, 0, bytes.Length);
  562. provider.Sent();
  563. }
  564. internal void Output(ApiProvider provider, ApiOptions options, ApiResponse response, ApiRequest request, HttpMethod method)
  565. {
  566. var preWrite = provider.PreWrite();
  567. if (!string.IsNullOrEmpty(preWrite)) return;
  568. if (response != null)
  569. {
  570. var responsePreOutput = response.PreOutput;
  571. if (responsePreOutput != null)
  572. {
  573. var @continue = responsePreOutput.Invoke(_context);
  574. if (!@continue) return;
  575. }
  576. }
  577. var invokerPreOutput = _context.Invoker.PreOutput;
  578. if (invokerPreOutput != null)
  579. {
  580. var @continue = invokerPreOutput.Invoke(_context);
  581. if (!@continue) return;
  582. }
  583. var optionsPreOutput = _context.Options.PreOutput;
  584. if (optionsPreOutput != null)
  585. {
  586. var @continue = optionsPreOutput.Invoke(_context);
  587. if (!@continue) return;
  588. }
  589. // 设置头。
  590. var headers = PrepareHeaders(options, response, request);
  591. foreach (var header in headers) provider.SetHeader(header.Key, header.Value);
  592. // 自定义模型
  593. var model = response.Model as IApiModel;
  594. var result = response.Model as IActionResult;
  595. if (model != null)
  596. {
  597. try
  598. {
  599. model.Output(_context);
  600. }
  601. catch (Exception ex)
  602. {
  603. Logger.Internals.Exception(model, ex);
  604. }
  605. RuntimeUtility.Dispose(model);
  606. return;
  607. }
  608. else if (result != null)
  609. {
  610. try
  611. {
  612. result.ExecuteResult(_context);
  613. }
  614. catch (Exception ex)
  615. {
  616. Logger.Internals.Exception(result, ex);
  617. }
  618. RuntimeUtility.Dispose(result);
  619. return;
  620. }
  621. var text = ApiUtility.ToJson(response, options);
  622. var bytes = TextUtility.Bytes(text);
  623. provider.SetCache(0);
  624. provider.SetContentType("text/json; charset=utf-8");
  625. provider.SetContentLength(bytes.Length);
  626. var stream = provider.ResponseBody();
  627. if (stream != null && stream.CanWrite) stream.Write(bytes, 0, bytes.Length);
  628. provider.Sent();
  629. }
  630. #endregion
  631. }
  632. }