From aa12fe2bdf674f9a666368e6bcd26553db88c660 Mon Sep 17 00:00:00 2001 From: Elivo Date: Mon, 6 Apr 2026 18:15:08 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=20ApiContext.Current?= =?UTF-8?q?=EF=BC=8C=E7=94=A8=E4=BA=8E=E8=8E=B7=E5=8F=96=E5=BD=93=E5=89=8D?= =?UTF-8?q?=E4=B8=8A=E4=B8=8B=E6=96=87?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Apewer/Web/ApiContext.cs | 39 +++++++++++++++++++++++++++++++++------ 1 file changed, 33 insertions(+), 6 deletions(-) diff --git a/Apewer/Web/ApiContext.cs b/Apewer/Web/ApiContext.cs index 9031f04..999a3c4 100644 --- a/Apewer/Web/ApiContext.cs +++ b/Apewer/Web/ApiContext.cs @@ -1,9 +1,6 @@ -using Apewer.Network; -using System; -using System.Collections.Generic; -using System.Diagnostics; +using System; using System.Reflection; -using System.Text; +using System.Threading; namespace Apewer.Web { @@ -69,6 +66,36 @@ namespace Apewer.Web #endregion + #region Current + +#if NET461_OR_GREATER || NETSTANDARD || NETCOREAPP + static AsyncLocal _current = new AsyncLocal(); +#endif + + static void SetCurrent(ApiContext context) + { +#if NET461_OR_GREATER || NETSTANDARD || NETCOREAPP + _current.Value = context; +#else + System.Runtime.Remoting.Messaging.CallContext.LogicalSetData("ApiContext", context); +#endif + } + + static ApiContext GetCurrent() + { +#if NET461_OR_GREATER || NETSTANDARD || NETCOREAPP + if (_current == null) return null; + return _current.Value; +#else + return System.Runtime.Remoting.Messaging.CallContext.LogicalGetData("ApiContext") as ApiContext; +#endif + } + + /// 获取当前的 实例。 + public static ApiContext Current { get => GetCurrent(); } + + #endregion + internal ApiContext(ApiInvoker invoker, ApiProvider provider, ApiEntries entries) { if (invoker == null) throw new ArgumentNullException(nameof(invoker)); @@ -78,9 +105,9 @@ namespace Apewer.Web _invoker = invoker; _provider = provider; _entries = entries; - _options = invoker.Options ?? new ApiOptions(); + SetCurrent(this); } /// 自定义数据。若此自定义数据实现了 ,将会与 Context 一起自动释放。