我有一个编写在ASP.NET MVC 5框架顶部的应用程序。
我创建了一个基本控制器,我的所有控制器都在其中。我的基本控制器看起来像这样
[Authorize]
public class BaseController : Controller
{
protected IFlashManager Flash { get; set; }
protected ICookie Cookie { get; set; }
protected ICacheClient Cache { get; set; }
protected override void Initialize(RequestContext requestContext)
{
base.Initialize(requestContext);
Cookie = new CookieJar(requestContext.HttpContext);
Flash = new FlashManager(TempData);
Cache = new StackExchangeRedisCacheClient(new NewtonsoftSerializer());
}
}
我想让全局Cookie
和Cache
对象可用于我的所有观看次数。
Microsoft已对User
对象做了同样的事情。
我可以在不使用ViewBag
或TempData
的情况下执行此操作吗?
答案 0 :(得分:2)
我创建了一个继承自WebViewPage<T>
。
InitHelpers()
以初始化这些属性。WebViewPage<T>
VB示例:
Imports System.Linq.Expressions
Public Class ProjectMvcViewPage(Of T)
Inherits WebViewPage(Of T)
Public Overrides Sub InitHelpers()
MyBase.InitHelpers()
Framework = New FrameworkHelper(Of T)(MyBase.ViewContext, Me)
End Sub
Public Overrides Sub Execute()
End Sub
Public Overloads Property Framework As FrameworkHelper(Of T)
End Class
Public Class ProjectMvcViewPage
Inherits ProjectMvcViewPage(Of Object)
End Class
Public Class FrameworkHelper(Of T)
Inherits HtmlHelper(Of T)
Public Sub New(ByVal viewContext As ViewContext, ByVal viewDataContainer As IViewDataContainer)
MyBase.New(viewContext, viewDataContainer)
End Sub
Public Sub New(ByVal viewContext As ViewContext, ByVal viewDataContainer As IViewDataContainer, ByVal routeCollection As RouteCollection)
MyBase.New(viewContext, viewDataContainer, routeCollection)
End Sub
' TODO: Framework-specific methods
End Class
Public Class FrameworkHelper
Inherits AkcHtmlHelper(Of Object)
Public Sub New(ByVal viewContext As ViewContext, ByVal viewDataContainer As IViewDataContainer)
MyBase.New(viewContext, viewDataContainer)
End Sub
Public Sub New(ByVal viewContext As ViewContext, ByVal viewDataContainer As IViewDataContainer, ByVal routeCollection As RouteCollection)
MyBase.New(viewContext, viewDataContainer, routeCollection)
End Sub
End Class
...并在Web.config中注册
<system.web.webPages.razor>
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<!--<pages pageBaseType="System.Web.Mvc.WebViewPage">-->
<pages pageBaseType="Project.ProjectMvcViewPage">
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Optimization"/>
<add namespace="System.Web.Routing" />
</namespaces>
</pages>
</system.web.webPages.razor>
答案 1 :(得分:0)
这可能有用。
HttpContext.Session.SetString("foo", "bar");
HttpContext.Session.GetString("foo");