我应该如何从 .NetCore2 中的模型访问 HttpContext? [英] How should I access HttpContext from a model in .NetCore2?

查看:19
本文介绍了我应该如何从 .NetCore2 中的模型访问 HttpContext?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的 UI 中使用 Dev Express AspxLtreeList 控件并将其绑定到来自 .NetCore2 API 的数据

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

我是 ASP 和 .NetCore 的新手

I am a fair newbie to both ASP and .NetCore

我可以吗?如果可以,我该如何将以下代码转换为 .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;
        }
    }
}

推荐答案

您需要找到一种方法将 IHttpContextAccessor 注入依赖类,因为 HttpContext.Current 不是在 .net-core 中可用.

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

通过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.

这篇关于我应该如何从 .NetCore2 中的模型访问 HttpContext?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆