【问题标题】:Handling cookies based on route in a single request lifecycle in ASP.NET MVC?在 ASP.NET MVC 的单个请求生命周期中处理基于路由的 cookie?
【发布时间】:2020-02-15 22:47:54
【问题描述】:

我正在编写一个路由,它允许用户使用应用程序将用于设置客户端配置的某个 JSON 对象的版本设置一个 cookie。这是一个相当大的 JSON 对象,我们不想单独存储在 cookie 中。我们只想在每个请求上存储要从云中的某个映射查找和设置的版本,因为客户端的多个版本正在运行,我们希望根据每个请求将它们分开。

目前,我知道问题是由于我对 ASP.NET MVC 的单个请求生命周期缺乏了解,因为我确信以下代码可以证明。我确实知道 Application_BeginRequest 操作可能在处理路由之前发生(如果我在这里错了,请纠正我),但我不确定它应该发生在哪里,以便在检索 cookie 之前填充它。我也不相信Application_EndRequest 会因为相同但相反的问题而更好。

任何和所有导致我理解生命周期的建议以及处理这种 cookie 值获取的适当操作都将受到欢迎!

// Working controller (cookie does get set, this is confirmed)
using System;
using System.Web;
using System.Web.Mvc;
using SMM.Web.Infrastructure.Filters;

namespace SMM.Web.Controllers
{
    [NoCache]
    public class SetCookieController : ApplicationController
    {
        private HttpCookie CreateVersionCookie(int versionId)
        {
            HttpCookie versionCookie = new HttpCookie("version_id");
            versionCookie.Value = versionId.ToString();
            return versionCookie;
        }

        public ActionResult SetCookie(int versionId)
        {
            Response.Cookies.Add(CreateVersionCookie(versionId));
            return Redirect("/");
        }
    }
}



// In Global.asax.cs (this does not work to get the cookie)
private void LoadSomeJsonFromACookie()
{
    HttpCookie someJsonThingCookie = HttpContext.Current.Request.Cookies["version_id"];
    string jsonVersion = (string)staticVersionCookie.Value;
    string json = FunctionToGetSomeJsonThingByVersion(jsonVersion); // This returns a stringified JSON object based on the jsonVersion supplied
    dynamic someJsonThing = JsonConvert.DeserializeObject<dynamic>(json);
    HttpContext.Current.Items["someJsonThing"] = someJsonThing;
}

protected void Application_BeginRequest(object sender, EventArgs e)
{
    RedirectToHttps();

    // some other redirects happen here

    LoadSomeJsonFromACookie();
}

【问题讨论】:

  • 您可能正在寻找Application_AcquireRequestState 事件。看看这个link
  • +1 以获得良好的链接。我之前曾使用该链接来查找其他“操作”或事件,例如Application_BeginRequest。我会给你一个 A 表示努力,但我希望看到使用来自链接的内容而不是将来可能会中断的链接的格式正确的答案。

标签: asp.net asp.net-mvc cookies routes lifecycle


【解决方案1】:

Application_BeginRequest 是正确的地方。由于在代码中,您可以看到我正在向根 / 发送重定向,它会在需要 cookie 之前设置 cookie。

【讨论】:

  • 您需要额外的重定向来设置 cookie?看起来是个糟糕的设计,建议你另找办法。
  • 不,重定向是功能请求的一部分,所以它刚刚成功。
猜你喜欢
  • 1970-01-01
  • 2010-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-15
相关资源
最近更新 更多