如何将对象从过滤器传递给操作方法?

时间:2018-03-16 08:59:10

标签: c# asp.net-mvc asp.net-core asp.net-core-mvc shopping-cart

我在购买ASP.NET Core应用程序中的购物车时遇到一些问题。我正在使用会话存储来执行此操作,但每次执行OnActionExecuted时,传递给过滤器的购物车对象都是空的。任何人都知道为什么?

会话过滤器类:

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 个答案:

答案 0 :(得分:1)

您正使用名称cart

将购物车传递给操作
context.ActionArguments["cart"] = _mand;

但是当您从操作方法访问它时,名称为mand

public IActionResult BonEdit(Winkelmand mand, NieuwViewModel model)

为了将其传递给动作方法,这两个名称必须匹配

context.ActionArguments["mand"] = _mand;
相关问题