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

查看:68
本文介绍了我应该如何从.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天全站免登陆