Wednesday, June 15, 2016

ASP.NET Core Async Context Data

With classical ASP.NET MVC (wow ASP.NET MVC is already classical), I use HttpContext.Items to pass context sensitive data from one layer to another or from one child control to another child control. Logged in user info is a typical use case for this scenario. On every request I used to get the user profile or user data and store that in the HttpContext and then use that user info throughout the current request.

With ASP.NET Core, HttpContext is not recommended. Further it is recommended to use async/await to take advantage of freeing threads. Please see my other blog “ASP.NET Core / MVC 6 HttpContext.Current” on how to use HttpContext to store the data as done earlier.

Instead of using HttpContext.Items, I decided to use Asynchronous context to pass the data from one layer to another. For this I wrote a static class which creates this context. I am also using this static class to pass the HttpContext also.

Here is the code I used to create the context and hold data in that context:

public static class NTContext
    {
        public static NTContextModel Context
        {
            get
            {
                return (NTContextModel)CallContext.LogicalGetData("MegaMineContext");
            }
            set
            {
                NTContextModel model = value;
                if (model == null)
                {
                    model = new NTContextModel();
                }

                NTContextModel contextModel = Context;

                if (contextModel == null)
                {
                    CallContext.LogicalSetData("MegaMineContext", model);
                }
                else
                {
                    contextModel = Mapper.Map<NTContextModel, NTContextModel>(model, contextModel);
                }

            }
        }

        public static HttpContext HttpContext
        {
            get
            {
                return (HttpContext)CallContext.LogicalGetData("HttpContext");
            }
            set
            {
                CallContext.LogicalSetData("HttpContext", value);
            }
        }

    }