代码之家  ›  专栏  ›  技术社区  ›  TimelordNeill

如何将对象从过滤器传递到动作方法?

  •  1
  • TimelordNeill  · 技术社区  · 6 年前

    我在ASP中实现购物车时遇到一些问题。NET核心应用程序。我正在使用会话存储来执行此操作,但每次 OnActionExecuted 执行时,传递给筛选器的cart对象为空。有人知道为什么吗?

    会话筛选器类:

    public class WinkelmandSessionFilter : ActionFilterAttribute
    {
        private Winkelmand _mand;
    
        public WinkelmandSessionFilter()
        {
        }
    
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            _mand = ReadCartFromSession(context.HttpContext);
            context.ActionArguments["cart"] = _mand;
            base.OnActionExecuting(context);
        }
    
        public override void OnActionExecuted(ActionExecutedContext context)
        {
            WriteCartToSession(_mand, context.HttpContext);
            base.OnActionExecuted(context);
        }
    
        private Winkelmand ReadCartFromSession(HttpContext context)
        {
            Winkelmand cart = context.Session.GetString("cart") == null ?
                new Winkelmand() : JsonConvert.DeserializeObject<Winkelmand>(context.Session.GetString("cart"));
            return cart;
        }
    
        private void WriteCartToSession(Winkelmand cart, HttpContext context)
        {
            context.Session.SetString("cart", JsonConvert.SerializeObject(cart));
        }
    }
    

    使用此筛选器的方法:

    [ServiceFilter(typeof(WinkelmandSessionFilter))]
    public IActionResult BonEdit(Winkelmand mand, NieuwViewModel model)
    {
        var bon = new Bon();
        bon.NaamGeadreseerde = model.naamGeadreseerde;
        bon.EmailGeadreseerde = model.emailGeadreseerde;
        bon.NaamGever = model.naamGever;
        bon.Bedrag = model.Bedrag;
        bon.Boodschap = model.Boodschap;
        bon.Winkel = model.Winkel;
        bon.BonId = Guid.NewGuid().GetHashCode();
        mand.bonToevoegen(bon);
        bon.genereerPdf();
        return RedirectToAction(nameof(BonVoorbeeld), bon);
    }
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   NightOwl888 Jabrwoky    6 年前

    您正在使用名称将购物车传递给操作 cart :

    context.ActionArguments["cart"] = _mand;
    

    但是当您从action方法访问它时,名称是 mand :

    public IActionResult BonEdit(Winkelmand mand, NieuwViewModel model)
    

    为了将其传递到action方法中,以下两个名称 必须匹配

    context.ActionArguments["mand"] = _mand;