在ASP.NET MVC中基于单个请求生命周期中的路由处理cookie?

问题描述 投票:0回答:1

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

[当前,我知道问题是由于我不了解ASP.NET MVC的单个请求生命周期,我确定以下代码可以证明。我确实知道Application_BeginRequest Action可能是在处理路由之前发生的(如果我在这里错了,请纠正我),但是我不确定应该在哪里发生,以便在检索Cookie之前填充该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();
}
asp.net asp.net-mvc cookies routes lifecycle
1个回答
0
投票

您可能正在寻找Application_AcquireRequestState事件。看看这个link

© www.soinside.com 2019 - 2024. All rights reserved.