-1

I am using a structure to create a dictionary for each user request and set a value in it.

Now my question is how can I safe store the value of each request in the global variable?

Part of my code in Global.asax ...



        protected async Task Application_BeginRequestAsync(object sender, EventArgs e)
        {
            var app = (HttpApplication)sender;
            var ctx = app.Context;

            if (Request.Url.Host.StartsWith("www") && !Request.Url.IsLoopback)
            {
                UriBuilder builder = new UriBuilder(Request.Url);
                builder.Host = Request.Url.Host.Replace("www.", "");
                Response.Redirect(builder.ToString(), true);
            }
            var domain = Request.Url.Host + ((Request.Url.Port != 80 && Request.Url.Port != 443) ? ":" + Request.Url.Port.ToString() : "");
            domain = domain.Replace("www.", "");

            ctx.Items["ShopKey"] = domain;
            .
            .
            .
             etc code...

}

What variable is appropriate for this, and is the http context appropriate?

and another question i have use http context but task run variable is null, how do I fix the problem?

thanks.

  • The HttpContext is scoped to the current request thread. When you start a new task on a new thread, it won't inherit the HttpContext. Further, if the background task lives longer than the HTTP request that started it, it will be disposed and stop working once the request ends if you capture it. – Martin Costello May 09 '22 at 10:19
  • @MartinCostello allright,how to set new context? or new safe variable new thread? – Ahmad Ghasemi May 09 '22 at 10:24
  • You can't really. Copy the values from the `HttpContext` you need into something else, and then pass _those_ to the background task. – Martin Costello May 09 '22 at 10:25
  • @MartinCostello No Unfortunately, the variable I use breaks down when a new task is created. Can I use a variable or something else? – Ahmad Ghasemi May 09 '22 at 10:28
  • You'll need to capture the values you need from the HTTP context into a new variable, and then pass that into the background task. – Martin Costello May 09 '22 at 10:31
  • @MartinCostello how to create new global variable safe that into the background task? – Ahmad Ghasemi May 09 '22 at 10:45
  • 1
    You wouldn't use a global variable. You would capture the values into a local variable and pass that into the Task you start. See https://stackoverflow.com/questions/30225476/task-run-with-parameters – Martin Costello May 09 '22 at 10:48

0 Answers0