我可以使用OwinContext在单个ASP*享数据吗?净MVC5应用程序?

时间:2022-01-14 04:10:01

I'd like to have specific static data (site menu DTO in particular) shared across all application requests. In the old system.web.dll days, that would be adding data in Application_Start into HttpContent.Current.Application[] dictionary. I'm sure very similar can be achieved with Owin / OwinContext but cannot find the easy way how to add it / access it. Can anyone help?

我希望在所有应用程序请求之间共享特定的静态数据(特别是site menu DTO)。在旧的包含。dll天,这将在Application_Start中添加数据到HttpContent.Current。应用[]字典。我确信在Owin / OwinContext中可以实现非常相似的功能,但是我无法找到如何添加/访问它的简单方法。谁能帮忙吗?

1 个解决方案

#1


2  

The Microsoft.AspNet.Identity.Owin library contains the class OwinContextExtensions which has the following methods:

Microsoft.AspNet.Identity。Owin库包含owincontext类,它有以下方法:

public static T Get<T>(this IOwinContext context)
{
  if (context == null)
  {
    throw new ArgumentNullException("context");
  }
  return context.Get<T>(OwinContextExtensions.GetKey(typeof(T)));    
}


public static T Set<T>(this IOwinContext context, T value)
{
  if (context == null)
  {
    throw new ArgumentNullException("context");
  }
  return context.Set<T>(OwinContextExtensions.GetKey(typeof(T)), value);
}

I'm pretty sure you can use these to set and get values stored in the OwinContext. Notice that the key name of the object stored in the context is the type, so for collections you should create a concrete type for the unique name:

我确信您可以使用它们来设置和获取存储在OwinContext中的值。注意,存储在上下文中的对象的键名是类型,因此对于集合,您应该为惟一名称创建一个具体的类型:

public MyDictionary : Dictionary<string, int>
{
}

var myDic = new MyDictionary();

var context = HttpContext.GetOwinContext();

context.Set(myDic);

var myDic2 = context.Get<MyDictionary>();

#1


2  

The Microsoft.AspNet.Identity.Owin library contains the class OwinContextExtensions which has the following methods:

Microsoft.AspNet.Identity。Owin库包含owincontext类,它有以下方法:

public static T Get<T>(this IOwinContext context)
{
  if (context == null)
  {
    throw new ArgumentNullException("context");
  }
  return context.Get<T>(OwinContextExtensions.GetKey(typeof(T)));    
}


public static T Set<T>(this IOwinContext context, T value)
{
  if (context == null)
  {
    throw new ArgumentNullException("context");
  }
  return context.Set<T>(OwinContextExtensions.GetKey(typeof(T)), value);
}

I'm pretty sure you can use these to set and get values stored in the OwinContext. Notice that the key name of the object stored in the context is the type, so for collections you should create a concrete type for the unique name:

我确信您可以使用它们来设置和获取存储在OwinContext中的值。注意,存储在上下文中的对象的键名是类型,因此对于集合,您应该为惟一名称创建一个具体的类型:

public MyDictionary : Dictionary<string, int>
{
}

var myDic = new MyDictionary();

var context = HttpContext.GetOwinContext();

context.Set(myDic);

var myDic2 = context.Get<MyDictionary>();