如何在APIController中使用Session

时间:2018-07-29 09:45:45

标签: c# asp.net-mvc session asp.net-apicontroller

我有一个存储List<Cart>值的APIController,并且我希望列表项持久存在,并希望使用Session将项目获取并发布到列表中,以便拉入视图以显示购物车项目。 / p>

由于我是Session新手,所以我不太确定该在哪里使用会话以及如何创建会话。

APIController:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using System.Web;
using System.Web.UI;
using Microsoft.AspNetCore.Http;
using fyp.Models;


namespace fyp.Controllers
{
    [Route("api/Cart")]
    public class CartAPIController : Controller
    {
        private List<Cart> cart = new List<Cart>()
        {
            new Cart {  CartId = 1,
                    FoodId = 6,
                    FoodName = "Beef & Tendon with Noodle",
                    quantity = 1,
                    price = 7},
            new Cart {  CartId = 1,
                    FoodId = 1,
                    FoodName = "Curry Beef Gravy with Beef Noodle",
                    quantity = 2,
                    price = 6}
        };


        // GET: api/<controller>
        [HttpGet]
        public IActionResult Get()
        {
            return Ok(cart);
        }

        // GET api/<controller>/5
        [HttpGet("{id}")]
        public string Get(int id)
        {
            return "value";
        }

        // POST api/<controller>
        [HttpPost]
        public IActionResult Post(Cart cart)
        {
            if (ModelState.IsValid)
            {
                this.cart.Add(
                    new Cart
                    {
                        CartId = cart.CartId,
                        FoodId = cart.FoodId,
                        FoodName = cart.FoodName,
                        quantity = cart.quantity,
                        price = cart.price
                    });
                return Ok();
            }
            else
            {
                return BadRequest();
            }
        }
    }
}

List<Cart>中的项目仅用于测试目的,但是如何在会话中实现空列表?

1 个答案:

答案 0 :(得分:-1)

This page提供有关如何在asp.net应用程序中使用session的信息。

似乎您基本上将现有的this.cart替换为Session["cart"],所以您的帖子变成了类似的内容:

    public IActionResult Post(Cart cart)
    {
        if (ModelState.IsValid)
        {
            Session["cart"].Add(
                new Cart
                {
                    CartId = cart.CartId,
                    FoodId = cart.FoodId,
                    FoodName = cart.FoodName,
                    quantity = cart.quantity,
                    price = cart.price
                });
            return Ok();
        }
        else
        {
            return BadRequest();
        }
    }