MVC ActionFilterAttribute - 从操作中获取值

时间:2016-09-10 14:21:57

标签: c# asp.net-core asp.net-core-mvc actionfilterattribute onactionexecuting

在MVC中,我有一个在Startup中注册的服务,我用它来验证这样的动作:

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    //services.AddCaching();
    services.AddSession();
    services.AddMvc();
    services.AddScoped<SessionDetails>();
    //services.AddTransient<IAppSettings, AppSettings>();
    services.AddSingleton(Configuration);

    services.AddSingleton(MobileUnitOfWork);
    //services.AddTransient<IMobileUnitOfWork, MobileUnitOfWork>();
    services.AddScoped<RoleItemKey>();

    //Custom Attributes
    services.AddScoped<SiteSetting>();
    services.AddScoped<ValidationService>();
    //services.AddScoped<RequestHelper>();

    //services.AddEntityFramework()
    //    .AddSqlServer()
    //    .AddDbContext<QuotesAppContext>(options => options.UseSqlServer(Configuration["Data:ConnectionString"]));
}

然后将其放在任何需要检查访问权限的地方。

控制器:

[ServiceFilter(typeof(ValidationService))]
public IActionResult MyDetails()
{
    ControllerContext.RouteData.Values.Add("RoleItemKey", "MOBILE_MYHOLIDAYS_PAGE");
    ControllerContext.RouteData.DataTokens.Add("RoleItemKey", "MOBILE_MYHOLIDAYS_PAGE");
    HttpContext.Session.SetString("RoleItemKey", "MOBILE_MYHOLIDAYS_PAGE");
    ViewBag.RoleItemKey = RoleItemKey.MOBILE_MYHOLIDAYS_PAGE;
    return View("~/Views/User/MyDetails.cshtml", GetDetailsModel());
}

我需要做的就是从ActionFilterAttribute读取的执行操作中传递一个值。 现在因为我需要并希望在Startup.cs中初始化服务我无法找到传递价值的方法 - 请告诉我我忽略的内容。

正如你所看到的,我已经尝试了routedata,会话信息......但是在ActionFilterAttribute中我无法读取的实际操作中设置的任何内容,它只是为所有操作返回null。

任何人都可以告诉我这个设置,我如何从正在执行的操作中读取值?

服务

public class ValidationService : ActionFilterAttribute
{    
    private IConfiguration _config;
    private IMobileUnitOfWork _services;
    private Controller _controller;
    private ActionExecutingContext _context;
    private readonly IHttpContextAccessor _contextAccessor;
    private ISession _session => _context.HttpContext.Session;
    public string Moons;

    public ValidationService(IConfiguration config, IMobileUnitOfWork unitOfWork)
    {
        _config = config;
        _services = unitOfWork;
    }

    /// <summary>
    /// Ensures the page is validated before being directed
    /// </summary>
    /// <param name="context"></param>
    public override void OnActionExecuting(ActionExecutingContext context)
    {
        var controller = context.Controller as Controller;
        var moo = controller.HttpContext.Session.GetString("CascadeSessionToken");
        var mos = controller.HttpContext.Session.GetString("RoleItemKey");
        _context = context;
        _controller = controller;
        _controller.ViewBag.LoggedIn = true;

        base.OnActionExecuting(context);
        Validate("");
   }

2 个答案:

答案 0 :(得分:0)

您需要使用HttpContext.Items。存储价值:

context.Items["key"] = value;

并获得价值

var value = context.Items["key"];

答案 1 :(得分:0)

解决了它。决定从初始化器中取出两个服务,然后从控制器中取出它们 - 现在我可以传递我所需的密钥。