using System; using System.Reflection; using System.Threading; namespace Apewer.Web { /// API 上下文。 public sealed class ApiContext { #region 构造参数 private ApiInvoker _invoker = null; private ApiProvider _provider = null; private ApiEntries _entries = null; private DateTime _beginning = DateTime.Now; private ApiOptions _options = null; /// 此上下文启动的时间。 public DateTime Beginning { get => _beginning; } /// API 调用器。 public ApiInvoker Invoker { get => _invoker; } /// API 提供程序。 public ApiProvider Provider { get => _provider; } /// API 入口集。 public ApiEntries Entries { get => _entries; } /// API 选项。 public ApiOptions Options { get => _options; } #endregion #region 执行过程中产生的内容 /// API 行为。 public ApiAction ApiAction { get; internal set; } /// API 请求。 public ApiRequest Request { get; internal set; } /// API 响应。 public ApiResponse Response { get; internal set; } /// API 控制器实例。 public ApiController Controller { get; internal set; } /// 执行的方法。 public MethodInfo MethodInfo { get; internal set; } #endregion #region 中间件 Action _middleware_callback = null; /// 设置中间件回调。 internal void SetMiddlewareCallback(Action callback) => _middleware_callback = callback; /// 继续执行。 public void Next() => _middleware_callback?.Invoke(this); #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)); if (provider == null) throw new ArgumentNullException(nameof(provider)); if (entries == null) throw new ArgumentNullException(nameof(entries)); _invoker = invoker; _provider = provider; _entries = entries; _options = invoker.Options ?? new ApiOptions(); SetCurrent(this); } /// 自定义数据。若此自定义数据实现了 ,将会与 Context 一起自动释放。 public object Data { get; set; } } }