本文介绍了ASPNET vNext ActionFilter和TempData的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建ASPNET vNext的ActionFilter。在此过滤器我想进入到TempData和ViewData的(无论是在控制器在以前的版本)。我覆盖的方法
公共覆盖无效OnActionExecuting(ActionExecutingContext filterContext)

I'm trying to create an ActionFilter in aspnet vNext. Within this filter I want to access to the TempData and the ViewData (both available in Controller in previous versions).I override the method public override void OnActionExecuting(ActionExecutingContext filterContext)

filterContext 我有控制器,但是是一个的代替 ControllerBase 。我预计一 ControllerBase 因为在MVC的以前版本的 ControllerContext (基类的ActionExecutingContext )是 ControllerBase 的是在CodePlex上的源代码。我明白,这可能是因为POCO控制器。

Into the filterContext I have the controller but is an object instead of ControllerBase. I was expected a ControllerBase because in previous versions of MVC the ControllerContext (the base class of ActionExecutingContext) was a ControllerBase, here is the source code in codeplex. I understand that this could be because the POCO controllers.

所以,问题是,如何可以访问到TempData和ViewData的如果控制器是一个对象。简单地做一个向下转换(像这样(控制器)filterContext.Controller ),或有做一个最好的办法。

So, the question is, how can access to the TempData and the ViewData if the controller is an object. Simply doing a downcasting (something like this (Controller)filterContext.Controller) or there's a best way to do it.

更新

这是我想达到如果的但ASPNET 5。

That I want to achieve if explain it in this blog post but with aspnet 5.

推荐答案

要访问的 TempData的从动作过滤器中,你可以得到调用的服务 ITempDataDictionary 从DI

To access TempData from within an action filter, you can get the service called ITempDataDictionary from DI.

要从DI得到这个服务,你既可以做类似 actionContext.HttpContext.RequestServices.GetRequiredService< ITempDataDictionary>从内部() OnActionExecuting 方法。你也可以使用建筑注入,如果你喜欢使用的 ServiceFilterAttribute

To get this service from DI, you could either do something like actionContext.HttpContext.RequestServices.GetRequiredService<ITempDataDictionary>() from within your OnActionExecuting method. You could also use construction inject if you like by using ServiceFilterAttribute.

注意:结果
。通过默认的TempData取决于会话功能(即TempData的数据存储在会议),所以你需要一些东西来得到它的工作。

NOTE:
TempData by default depends on Session feature(i.e TempData's data is stored in Session) and so you need to few things to get it working.


  • 参考 Microsoft.AspNet.Session Microsoft.Framework.Caching.Memory

在你的 ConfigureServices 方法,执行以下操作:

In your ConfigureServices method, do the following:

services.AddCaching();
services.AddSession();


  • 在你的配置方法,注册会话中间件(这是它创建/附加一个会话到传入的请求的名称)和前的做到这一点的注册MVC。

  • In your Configure method, register the Session middleware (this is the one which creates/attaches a session to the incoming requests) and do it before registering MVC.

    app.UseSession();
    app.UseMvc(...)
    


  • 这篇关于ASPNET vNext ActionFilter和TempData的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

    11-03 14:04