MVC ActionFilterAttribute -从动作中获取一个值

本文关键字:一个 获取 ActionFilterAttribute MVC | 更新日期: 2023-09-27 18:06:24

在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, session info…但是无论在实际操作中设置什么,我都无法在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("");
   }

MVC ActionFilterAttribute -从动作中获取一个值

你需要使用HttpContext。项目。存储值:

context.Items["key"] = value;

和返回值

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

已解析。我决定从初始化器中取出这两个服务,并从控制器中获取它们——现在我可以传入所需的键了。