首页 > 解决方案 > C# - ASP.NET MVC - 将对象列表转换为字符串列表,以在会话中使用

问题描述

我有那个类型的列表:

IEnumerable<Resource> ResourceAuthorizedForLoggedUser= resourceAuthorizer.FindAll();

首先尝试一下,但没有奏效:

var authorizations= ResourceAuthorizedForLoggedUser.Select(x => x.Id).ToString();

我需要放入该会话中:

System.Web.HttpContext.Current.Session["Authorized_List"] = authorizations;

能够在基本控制器中访问此数据

public class BaseController : Controller
{
   public static List<string> authorizations { get { return Getauthorizations(); } }

   private static List<string> Getauthorizations()
   {
      List<string> authorizationsList = (List<string>)System.Web.HttpContext.Current.Session["Authorized_List"];
      return authorizationsList != null && authorizationsList.Any() ? authorizationsList : new List<string>();
   }
}

最后,我在Getauthorizations方法中收到以下错误:

无法将“System.String”类型的对象转换为“System.Collections.Generic.List`1 [System.String]”类型

有什么想法可以转换该列表吗?

标签: c#asp.net-mvcsession

解决方案


我会写你的代码如下:

  1. 首先,您获得了 Resource 类型的集合:
 IEnumerable<Resource> ResourceAuthorizedForLoggedUser=
 resourceAuthorizer.FindAll();
  1. 然后保存 ID 列表(我假设它们是字符串)
 List<string> authorizations=
 ResourceAuthorizedForLoggedUser.Select(x=> x.Id).ToList();
  1. 将其保存在会话变量中:
 System.Web.HttpContext.Current.Session["Authorized_List"] =
 authorizations;
  1. 从 Session 中读回:
public class BaseController : Controller
     {
        public static List<string> authorizations { get { return Getauthorizations(); } }


   private static List<string> Getauthorizations()
   {
      List<string> authorizationsList = (List<string>)System.Web.HttpContext.Current.Session["Authorized_List"];
      return authorizationsList != null && authorizationsList.Any() ? authorizationsList : new List<string>();
   }
}`enter code here`

推荐阅读