Kirsten
Kirsten

Reputation: 18076

How should I access HttpContext from a model in .NetCore2?

I want to use the Dev Express AspxLtreeList control in my UI and bind it to data from a .NetCore2 API

I am a fair newbie to both ASP and .NetCore

Can I , and if so how do I translate the following code to .NetCore?

using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace TreeListDragDropMultipleNodes.Models
{
    public class Data
    {
        public int ID { set; get; }
        public int ParentID { set; get; }
        public string Title { set; get; }
    }

    public static class DataHelper
    {
        public static List<Data> GetData()
        {
            List<Data> data = HttpContext.Current.Session["Data"] as List<Data>;

            if (data == null)
            {
                data = new List<Data>();

                data.Add(new Data { ID = 1, ParentID = 0, Title = "Root" });

                data.Add(new Data { ID = 2, ParentID = 1, Title = "A" });
                data.Add(new Data { ID = 3, ParentID = 1, Title = "B" });
                data.Add(new Data { ID = 4, ParentID = 1, Title = "C" });

                data.Add(new Data { ID = 5, ParentID = 2, Title = "A1" });
                data.Add(new Data { ID = 6, ParentID = 2, Title = "A2" });
                data.Add(new Data { ID = 7, ParentID = 2, Title = "A3" });

                data.Add(new Data { ID = 8, ParentID = 3, Title = "B1" });
                data.Add(new Data { ID = 9, ParentID = 3, Title = "B2" });

                data.Add(new Data { ID = 10, ParentID = 4, Title = "C1" });

                data.Add(new Data { ID = 11, ParentID = 8, Title = "B1A" });
                data.Add(new Data { ID = 12, ParentID = 8, Title = "B1B" });

                HttpContext.Current.Session["Data"] = data;
            }

            return data;
        }

        public static void MoveNodes(int[] nodeKeys, int parentID)
        {
            var data = GetData();
            var processedNodes = data.Join(nodeKeys, x => x.ID, y => y, (x, y) => x);

            foreach(var node in processedNodes)
            {
                if (processedNodes.Where(x => x.ID == node.ParentID).Count() == 0)
                {
                    if (node.ParentID == 0)
                    {
                        MakeParentNodeRoot(parentID);
                    }
                    node.ParentID = parentID;
                }
            }
        }

        public static void MoveNode(int nodeID, int parentID)
        {
            var data = GetData();

            var node = data.Find(x => x.ID == nodeID);

            if (node.ParentID == 0)
            {
                MakeParentNodeRoot(parentID);
            }

            node.ParentID = parentID;
        }

        public static void MakeParentNodeRoot(int id)
        {
            GetData().Find(x => x.ID == id).ParentID = 0;
        }
    }
}

Upvotes: 0

Views: 1230

Answers (1)

Nkosi
Nkosi

Reputation: 246998

You will need to find a way inject IHttpContextAccessor into the dependent class as HttpContext.Current is not available in .net-core.

To convert the current code first refactor the helper to not be static and it should also be backed by an abstraction/interface

public interface IDataHelper {
    List<Data> GetData();
    void MoveNodes(int[] nodeKeys, int parentID);
    void MoveNode(int nodeID, int parentID);
    void MakeParentNodeRoot(int id);
}

Have the class follow explicit dependency via constructor injection for IHttpContextAccessor

public class DataHelper : IDataHelper {
    private readonly IHttpContextAccessor accessor;

    public DataHelper(IHttpContextAccessor accessor) {
        this.accessor = accessor;
    }

    public List<Data> GetData() {
        List<Data> data = accessor.HttpContext.Session.Get<List<Data>>("Data");

        if (data == null) {
            data = new List<Data>();
            data.Add(new Data { ID = 1, ParentID = 0, Title = "Root" });
            data.Add(new Data { ID = 2, ParentID = 1, Title = "A" });
            data.Add(new Data { ID = 3, ParentID = 1, Title = "B" });
            data.Add(new Data { ID = 4, ParentID = 1, Title = "C" });
            data.Add(new Data { ID = 5, ParentID = 2, Title = "A1" });
            data.Add(new Data { ID = 6, ParentID = 2, Title = "A2" });
            data.Add(new Data { ID = 7, ParentID = 2, Title = "A3" });
            data.Add(new Data { ID = 8, ParentID = 3, Title = "B1" });
            data.Add(new Data { ID = 9, ParentID = 3, Title = "B2" });
            data.Add(new Data { ID = 10, ParentID = 4, Title = "C1" });
            data.Add(new Data { ID = 11, ParentID = 8, Title = "B1A" });
            data.Add(new Data { ID = 12, ParentID = 8, Title = "B1B" });

            accessor.HttpContext.Session.Set("Data", data);
        }

        return data;
    }

    public void MoveNodes(int[] nodeKeys, int parentID) {
        var data = GetData();
        var processedNodes = data.Join(nodeKeys, x => x.ID, y => y, (x, y) => x);

        foreach(var node in processedNodes) {
            if (processedNodes.Where(x => x.ID == node.ParentID).Count() == 0) {
                if (node.ParentID == 0) {
                    MakeParentNodeRoot(parentID);
                }
                node.ParentID = parentID;
            }
        }
    }

    public void MoveNode(int nodeID, int parentID) {
        var data = GetData();
        var node = data.Find(x => x.ID == nodeID);
        if (node.ParentID == 0) {
            MakeParentNodeRoot(parentID);
        }
        node.ParentID = parentID;
    }

    public void MakeParentNodeRoot(int id) {
        GetData().Find(x => x.ID == id).ParentID = 0;
    }
}

Some additional extension would be needed to store the data in the session

//Extensions used to stores complex objects as JSON string in session
public static class SessionExtensions {
    public static void Set(this ISession session, string key, object value) {
        session.SetString(key, JsonConvert.SerializeObject(value));
    }

    public static T Get<T>(this ISession session, string key) {
        var value = session.GetString(key);
        return value == null ? default(T) : JsonConvert.DeserializeObject<T>(value);
    }
}

Configure the service collection to allow the needed dependencies to be resolved when requested.

services.AddScoped<IDataHelper, DataHelper>();
services.AddHttpContextAccessor();//IHttpContextAccessor is not added by default.

Any class that was dependent on the data helper would now also need to be refactored to depend on its abstraction.

This allows the code to be cleaner and more manageable as it will be decoupled from static implementation concerns.

Upvotes: 3

Related Questions