Blairg23
Blairg23

Reputation: 12065

Handling cookies based on route in a single request lifecycle in ASP.NET MVC?

I'm writing a route that will allow the user to set a cookie with the version of some JSON object that the application will use to set client-side configurations. It is a fairly large JSON object that we don't want to store in a cookie alone. We want to store ONLY the version to be looked up and set from some map up in the cloud on every request since multiple versions of the client are running around and we want those to be separated on a per request basis.

Currently, I know the problem is due to my lack of understanding of the single request lifecycle of ASP.NET MVC as I'm sure the following code proves. I do know that the Application_BeginRequest Action is probably happening BEFORE the route is handled (correct me if I'm wrong here), but I am not sure where it SHOULD be happening so that the cookie is populated BEFORE it is retrieved. I also don't believe that Application_EndRequest would be better due to the same, but opposite issue.

Any and all suggestions that lead to my understanding of the lifecycle and an appropriate Action to handle that kind of cookie value getting will be welcomed!

// 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();
}

Upvotes: 0

Views: 354

Answers (1)

Blairg23
Blairg23

Reputation: 12065

Application_BeginRequest is the right place. Since in the code, you can see I'm firing a redirect back to root /, it will set the cookie before it ever needs the cookie.

Upvotes: 1

Related Questions