在asp.net mvc中将cookie值存储在全局变量中

发布于 2024-12-03 11:18:58 字数 176 浏览 0 评论 0原文

我有一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

£烟消云散 2024-12-10 11:18:58

一般来说,控制器和动作对外部提供的值的依赖程度越高,它们的单元测试性和鲁棒性就越高。我会这样做

首先,创建保存时区设置的模型

public class ClientTimeZoneSettings
{
   public string TimeZoneName {get; set;} // or whatever
}

然后,创建模型绑定器。该模型绑定器将用于从 cookie 中提取值

public class ClientTimeZoneSettingsModelBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        if (controllerContext.RequestContext.HttpContext.Request.Cookies.AllKeys.Contains("timeZoneName"))
        {
            bindingContext.Model = new ClientTimeZoneSettings {TimeZoneName = controllerContext.RequestContext.HttpContext.Request.Cookies["timeZoneName"]; }
        }

    }
}

在 Global.asax 中注册该模型绑定器

protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();

RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);


ModelBinders.Binders.Add(typeof(ClientTimeZoneSettings), new ClientTimeZoneSettingsModelBinder());

}

以及要点。在需要这些设置的所有操作中,您可以直接使用 ClientTimeZoneSettings 作为参数

public ActionResult ShowComments(ClientTimeZoneSettings settings)
{
  // use settings
}

更新:明显更简单的方法:

安装MvcFutures 来自 nuget。它包含 CookieValueProviderFactory,它将在模型绑定时自动检查 cookie 中的值。要使用它,只需添加到 ValueProviderFactories

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();

    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);

    ValueProviderFactories.Factories.Add(new CookieValueProviderFactory());
}

,然后根据 cookie 名称命名您的参数

public ActionResult ShowComments(string timeZoneName)
{
    // timeZoneName will contain your cookie value
    return View();
}

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

public class ClientTimeZoneSettings
{
   public string TimeZoneName {get; set;} // or whatever
}

Then, create model binder. That Model binder will be used to extract values from cookie

public class ClientTimeZoneSettingsModelBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        if (controllerContext.RequestContext.HttpContext.Request.Cookies.AllKeys.Contains("timeZoneName"))
        {
            bindingContext.Model = new ClientTimeZoneSettings {TimeZoneName = controllerContext.RequestContext.HttpContext.Request.Cookies["timeZoneName"]; }
        }

    }
}

Register that model binder in Global.asax

protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();

RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);


ModelBinders.Binders.Add(typeof(ClientTimeZoneSettings), new ClientTimeZoneSettingsModelBinder());

}

And the main point. In all your actions that require those settings, you can directly use ClientTimeZoneSettings as a parameter

public ActionResult ShowComments(ClientTimeZoneSettings settings)
{
  // use settings
}

UPDATE: 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 into ValueProviderFactories

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();

    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);

    ValueProviderFactories.Factories.Add(new CookieValueProviderFactory());
}

And then name your parameter accorting to cookie name

public ActionResult ShowComments(string timeZoneName)
{
    // timeZoneName will contain your cookie value
    return View();
}
殤城〤 2024-12-10 11:18:58

如果您不想每次都使用 cookie,则可以使用会话变量

session["MyVarName"] = mycookievalue

,这样您就可以在每次需要时访问会话。

您还可以考虑实现自定义模型绑定器,以便将会话的值绑定到模型。 (例如 UserSettingsModel 类)

You can use a session variable if you don't want to use the cookie every time

session["MyVarName"] = mycookievalue

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)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文