c# - 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]”类型
有什么想法可以转换该列表吗?
解决方案
我会写你的代码如下:
- 首先,您获得了 Resource 类型的集合:
IEnumerable<Resource> ResourceAuthorizedForLoggedUser= resourceAuthorizer.FindAll();
- 然后保存 ID 列表(我假设它们是字符串)
List<string> authorizations= ResourceAuthorizedForLoggedUser.Select(x=> x.Id).ToList();
- 将其保存在会话变量中:
System.Web.HttpContext.Current.Session["Authorized_List"] = authorizations;
- 从 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`
推荐阅读
- java - 在 java 中使用 if/else 返回一个布尔值
- c# - 按下按钮时如何更改文本框中的文本?
- scala - 如何组合两个具有 zio 效果和不同类型环境的 Http4s 路由
- ios - Firebase 函数 iOS 返回未找到错误
- java - Java游戏循环FPS问题
- javascript - 使用 v-html 渲染时 @click 不起作用
- javascript - 欢迎信息,“发送”有时显示为未定义
- react-native - react-native-camera 如何检测设备上的camera2 API是否可用?
- reactjs - 如何访问问号后的查询参数?
- sql - 存储过程执行顺序