简体   繁体   English

在ASP.NET MVC中存储跨页面的公共日期

[英]Store common date accross pages in ASP.NET MVC

Im using a base controller & OnActionExecuting to get 'common' site data that I want to show & keep accross most page's (name, ID etc... not more than 4/5 fields) 我使用基本控制器和OnActionExecuting来获取我想要显示的“常见”网站数据并保持在大多数网页上(名称,ID等...不超过4/5字段)

The Method in OnActionExecuting reads the database & saves to ViewBag which Ipick up in my Views but I cant help thinking this is a waste as it needs a DB call for every OnActionExecuting. OnActionExecuting中的方法读取数据库并保存到我的视图中提取的ViewBag,但我不能认为这是一种浪费,因为它需要每次OnActionExecuting的DB调用。

How can consolodate these DB calls and slim down the DB access? 如何整合这些数据库调用并减少数据库访问?

缓存存储库层中的公共数据值。

What I have done on a recent project is during Login I get the 'common' data which in this case was UserID, FirstName and an ImageName, I saved it in the Auth Ticket like this : 我在最近的项目中所做的是在登录期间我得到'常见'数据,在这种情况下是UserID,FirstName和ImageName,我将它保存在Auth Ticket中,如下所示:

UserData = pModel.PartyId.ToString() + "|" + pModel.BusinessName + "|" + pModel.FirstName + "|" + pModel.LastName + "|" + pModel.ImageUrl + "|" + UsersRole + "|" + IsAct;//PID, BusName, FirstName, LastName, imgUrl, Role, IsAct

// Create the cookie that contains the forms authentication ticket
HttpCookie authCookie = FormsAuthentication.GetAuthCookie(UN, true);
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);
FormsAuthenticationTicket newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, UserData);
authCookie.Value = FormsAuthentication.Encrypt(newTicket);
System.Web.HttpContext.Current.Response.Cookies.Add(authCookie);

I then retreive this Cookie when the data is needed and get the data out of it like this : 然后我在需要数据时检索这个Cookie并从中获取数据,如下所示:

var cookie = context.Request.Cookies[FormsAuthentication.FormsCookieName];
dynamic UN = FormsAuthentication.Decrypt(cookie.Value);
string UserData = UN.UserData;//PID, BusName, FirstName, LastName, imgUrl, Role, IsAct
string[] pFields = UserData.Split('|');
string[] MyRoles = { pFields[5] };

Please Note : This is only good for static data that you know wont change during the login session & be careful what you post in this Cookie. 请注意:这仅适用于您在登录会话期间不会更改的静态数据,并且要小心您在此Cookie中发布的内容。

Don't bloat the cookie either keep the fields to a minimum, max is 4K but I aim for 500-1000 bytes. 不要膨胀cookie要么保持字段最小,最大是4K但我的目标是500-1000字节。

Inheriting from a base controller does not mean that you have shared state across requests. 从基本控制器继承并不意味着您在请求之间具有共享状态。 Each request will result in a new controller instance. 每个请求都将生成一个新的控制器实例。

You need to store this data in some state (cache, session, application) if you don't want to retrieve it every time. 如果您不想每次都检索它,则需要将此数据存储在某种状态(缓存,会话,应用程序)中。 Then you can make whatever mechanism you store it in accessible from your base controller. 然后,您可以通过基本控制器访问存储它的任何机制。

Then there's the disclaimer...are these trips to the database expensive? 然后是免责声明......这些数据库的旅行费用昂贵吗? Are you going to trade minimal latency problems for memory management issues? 您是否要针对内存管理问题交换最小延迟问题?

UPDATE: 更新:

If it is just 4-5 fields (which appear to be user specific, and like they are not going to change during a user's session), then I'd just store them in session state. 如果它只是4-5个字段( 看起来是用户特定的,并且在用户会话期间它们不会改变),那么我只是将它们存储在会话状态中。

Personal preference here, but I like to have strongly typed accessors in base controllers/pages for things like this: 个人喜好在这里,但我喜欢在基本控制器/页面中有强类型访问器,如下所示:

    protected string Name
    {
        get
        {
            if (Session["Name"] == null)
            {
                var results = GoLoadFields();                    
                return Session["Name"].ToString();
            }

            return Session["Name"].ToString();
        }

        set
        {
            Session["Name"] = value;
        }
    }

Then in all of your controllers that inherit from your base controller can just reference these properties: 然后,从您的基本控制器继承的所有控制器都可以引用这些属性:

myAwesomeViewModel.Name = this.Name;

The memory management disclaimer is meant to have you avoid querying the database, getting the same large result set, and shoving it in the session for each user. 内存管理免责声明旨在让您避免查询数据库,获取相同的大结果集,并在每个用户的会话中推送它。 Before you keep anything around in memory, just make sure you're only keeping what you need and for how long you need it. 在记忆中保留任何东西之前,请确保只保留您需要的东西以及您需要的时间。

You can use System.Runtime.Caching.MemoryCache for this purpose. 您可以使用System.Runtime.Caching.MemoryCache来实现此目的。

Some examples: 一些例子:

The cache will persist across requests until the expiration for each cache item is reached. 缓存将在请求之间保持不变,直到达到每个缓存项目的到期时间。

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

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