我的 API 的自定义身份验证从数据库填充实体。如何与我的 Controller 共享这个特定于请求的对象(在下面的情况下为“映射”),以便我不必两次查询数据库以获得相同的信息?
public class CustomAuth : Attribute, IAuthenticationFilter, IDisposable
{
public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken){
var query = _readEntities.Query<API_Exe_Mapping>();
var mapping = await query.FirstOrDefaultAsync(...);
...
}
最佳答案
使用 HttpRequestMessage.Properties
您可以像这样使用 HttpRequesteMessage.Properties
属性:
public async Task AuthenticateAsync(HttpAuthenticationContext context, System.Threading.CancellationToken cancellationToken)
{
// your code here
context.Request.Properties["MyDataKey"] = new List<string> { "from my properties" };
}
然后在你的 Controller 中你只需使用以下代码:
var data = this.ActionContext.Request.Properties["MyDataKey"];
针对每个 http 请求都会清理该集合。
使用 HttpContext.Current.Items
您可以使用以下解决方案之一,它将使用静态属性HttpContext.Current.Items
public async Task AuthenticateAsync(HttpAuthenticationContext context, System.Threading.CancellationToken cancellationToken)
{
// your code here
HttpContext.Current.Items["MyDataKey"] = new List<string> { "from my items" };
}
然后在您的 Controller 中,您只需检查相同的字典集合 HttpContext.Current.Items
并使用相同的键检索数据。当 http 请求终止时,Items
集合将被清除。
关于c# - 将请求特定的对象从自定义身份验证过滤器共享到 Controller /模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35588592/