在asp.net mvc中将cookie值存储在全局变量中
我有一个 ASP.NET MVC 博客,为了显示客户端时区中的帖子和评论日期,使用了 cookie,该 cookie 包含客户端时区偏移量。当服务器收到请求时,它将从 cookie 中读取偏移值并相应地更改所有日期,然后再发送到浏览器。我的问题是如何在每次请求时将 cookie 存储在全局变量中,以便可以在任何位置访问它以进行日期调整。
I've an ASP.NET MVC blog, in order to show the posts and comments dates in client timezone a cookie is used, the cookie contains the client timezone offset. When the server receives a request it will read the offset value from cookie and changes all the dates accordingly before sending to browser. My question how I can store the cookie in a global variable on every request so that it can be accessed by any where for date adjustment.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一般来说,控制器和动作对外部提供的值的依赖程度越高,它们的单元测试性和鲁棒性就越高。我会这样做
首先,创建保存时区设置的模型
然后,创建模型绑定器。该模型绑定器将用于从 cookie 中提取值
在 Global.asax 中注册该模型绑定器
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
}
以及要点。在需要这些设置的所有操作中,您可以直接使用
ClientTimeZoneSettings
作为参数更新:明显更简单的方法:
安装MvcFutures 来自 nuget。它包含 CookieValueProviderFactory,它将在模型绑定时自动检查 cookie 中的值。要使用它,只需添加到
ValueProviderFactories
中,然后根据 cookie 名称命名您的参数
Generally, the more controller and action depend on values supplied from outside, the more unit testable and robust they become. I would do it this way
First, create model that holds settings for timezone
Then, create model binder. That Model binder will be used to extract values from cookie
Register that model binder in Global.asax
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
}
And the main point. In all your actions that require those settings, you can directly use
ClientTimeZoneSettings
as a parameterUPDATE: Significantly simpler approach:
Install MvcFutures from nuget. It contains
CookieValueProviderFactory
that will automatically inspect cookies for values when model binding. To use it, simply add intoValueProviderFactories
And then name your parameter accorting to cookie name
如果您不想每次都使用 cookie,则可以使用会话变量
,这样您就可以在每次需要时访问会话。
您还可以考虑实现自定义模型绑定器,以便将会话的值绑定到模型。 (例如 UserSettingsModel 类)
You can use a session variable if you don't want to use the cookie every time
then you can access the session every time needed.
You can also think of implementing e custom modelbinder so you can bind your session's value to a model. (for example a class UserSettingsModel)