简体   繁体   English

ASP.NET中的Per-Request静态数据

[英]Per-Request static data in ASP.NET

I'm wanting to cache the roles a user is in for each request that comes in. There are several places throughout any given page where where we have something like: 我想要为每个请求缓存用户所处的角色。在任何给定页面中有几个地方我们有类似的地方:

<% if(Roles.IsUserInRole("RoleName")) {%>
    <!-- Conditional Rendering -->
<% } else if(Roles.IsUserInRole("AnotherRole") {%>
    <!-- You get the point -->
<% } %>

Since this is all stored in a sql database, each of these requests hit the database. 由于这都存储在sql数据库中,因此每个请求都会访问数据库。 I know there are ways to cache the roles in a cookie, but I don't want to do that. 我知道有办法在cookie中缓存角色,但我不想这样做。 Anyway, What I was thinking was something like this. 无论如何,我在想的是这样的。

public static class SecurityUtils
    {
        public static string[] UserRoles()
        {
            var context = HttpContext.Current;

            if (context == null) return Enumerable.Empty<string>();

            string[] roles;

            roles = context.Items["UserRoles"] as string[];

            if (roles == null)
            {
                roles = Roles.GetRolesForUser();
                context.Items["UserRoles"] = roles;
            }

            return roles;
        }
    }

Anyone see any issues with this? 有人看到任何问题吗? I know that ever call to UserRoles() will lookup the item in the context and maybe this isn't the most effecient thing to do. 我知道,调用UserRoles()会在上下文中查找项目,也许这不是最有效的事情。 What I really want to know is if this will cache it on a per-request basis so there's no overlap with other users request. 我真正想知道的是,这是否会基于每个请求缓存它,因此与其他用户请求没有重叠。

That looks safe enough at a quick glance. 这看起来很安全,快速浏览一下。 HttpContext.Current.Items is a per-HTTP request cache. HttpContext.Current.Items是一个每HTTP请求缓存。 Another option to consider to further reduce database calls would be to use session state. 考虑进一步减少数据库调用的另一个选择是使用会话状态。

Consider a scenario where you have a page with a lot of ajax stuff going on. 考虑一个场景,其中有一个页面包含大量的ajax内容。 Each ajax request will invoke a database call to load security roles, since they are all separate HTTP requests. 每个ajax请求都将调用数据库调用来加载安全角色,因为它们都是单独的HTTP请求。

It will cache it per request, since you are using the current HttpContext . 它将根据请求缓存它,因为您正在使用当前的HttpContext

If you were using a static member, it would be cached till the web application was recycled. 如果您使用静态成员,它将被缓存,直到Web应用程序被回收。

As such it looks fine - a fairly common pattern in fact (using a static member as an in-memory cache or the current HttpContext ). 因此它看起来很好 - 实际上是一个相当常见的模式(使用静态成员作为内存缓存或当前的HttpContext )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM