效果:
步骤:
1、打开vs2019创建项目,选择asp.net core web 应用程序,选择API,开始创建
2、点项目右键,在管理NuGet程序包选择EF,添加图片
3、选择vs工具的管理NuGet程序,在选择程序包管理器控制台
4、输入:Scaffold-DbContext ‘Data Source=.;Initial Catalog=ShoppingDB; Integrated Security=True;’ Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Context ShopContext
这里需要注意的是:ShoppingDB是数据库的名称, ShopContext是上下文
5、在appsettings.json添加
"ConnectionStrings": {
"shopdb": "Data Source=.;Initial Catalog=ShoppingDB;Integrated Security=True;"
},
6、在Startup.cs 文件里面的public void ConfigureServices(IServiceCollection services)添加
services.AddDbContext<ShopContext>(options =>
{
options.UseSqlServer(Configuration.GetConnectionString("shopdb"));
});
注意:shopdb是appsettings.json里面添加的shopdb
7、在Controllers文件夹添加控制器,选择空的api,添加路由 [Route(“api/[controller]/[action]”)]
注意,如果不加api,这个接口是不能正确显示数据的
页面代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using WebAPI.Models;
namespace WebAPI.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class ProductsController : ControllerBase
{
private readonly ILogger<ProductsController> _logger;
ShopContext db;
public ProductsController(ILogger<ProductsController> logger, ShopContext shopContext)
{
_logger = logger;
db = shopContext;
}
//获得所有商品
[HttpGet]
public IEnumerable<Models.Products> GetAllProducts()
{
return db.Products.ToList();
}
}
}
接下来在解决方案上面添加新的项目,选择asp.net Core web应用程序,选择web应用程序(模型视图控制器)
把api里面生成的models的实体类拷贝到mvc的model里面,别忘记改命名空间
1、在NuGet程序包添加Newtonsoft.Json
2、在控制器的index页面添加
//显示页面数据
public async Task<IActionResult> Index()
{
HttpClient httpClient = new HttpClient();
Task<string> task = httpClient.GetStringAsync("https://localhost:5001/api/Products/GetAllProducts");
var result = await task;
list = JsonConvert.DeserializeObject<IEnumerable<Products>>(result);
return View(list);
}
3、Index.cshtml 页面如下:
@{
ViewData["Title"] = "Home Page";
}
<h1>商品列表</h1>
<table class="table table-striped table-hover">
<tr>
<th>商品名称</th>
<th>商品价格</th>
<th>操作</th>
</tr>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>@item.Name</td>
<td>@string.Format("{0:C}元", item.Price)</td>
<td><a href="@Url.Action("Detils","Home",new { id=item.Id})" class="btn btn-primary btn-lg">添加到购物车</a></td>
</tr>
}
</tbody>
</table>
4、先把api设为启动项,启动步调试,在设置mvc为启动项,启动步调试,页面就可以显示出来了
5、打开redis的服务,先找到redis的目录输入redis-server redis.windows.conf 指令
6、先声明 RedisCache redisClient = null;
在控制器的构造方法里面添加
//创建Redis客户端对象
RedisCacheOptions options = new RedisCacheOptions()
{
InstanceName = "MyRedis",
Configuration = "127.0.0.1:6379,abortConnect=false"
};
redisClient = new RedisCache(options);
7、实现添加购物和删除购物车的方法和页面
static IEnumerable<Products> list = null;
static List<Products> listnew = new List<Products>();
static Dictionary<string, int> dis = new Dictionary<string, int>();
//实现购物车添加
public async Task<IActionResult> Detils(int id)
{
int num = 1;
string result = string.Empty;
if (list != null)
{
foreach (var item in list)
{
if (item.Id == id)
{
if (!listnew.Contains(item))
{
listnew.Add(item);
dis.Add(item.Name,num);
}
else
{
if (dis.ContainsKey(item.Name))
{
int num_1 = dis[item.Name];
++num_1;
dis[item.Name] = num_1;
}
}
var json = JsonConvert.SerializeObject(dis);
redisClient.SetString("newProd", json);
}
}
}
var data = redisClient.GetString("newProd");
ViewBag.Prod = JsonConvert.DeserializeObject(data);
//ViewBag.Result = db.StringGet("hash");
return View(listnew);
}
//实现购物车减少
public async Task<IActionResult> Delete(int id)
{
string result = string.Empty;
if (list != null)
{
foreach (var item in list)
{
if (item.Id == id)
{
if (listnew.Contains(item))
{
if (dis.ContainsKey(item.Name))
{
int num_1 = dis[item.Name];
--num_1;
dis[item.Name] = num_1;
if (num_1 == 0)
{
listnew.Remove(item);
}
}
}
var json = JsonConvert.SerializeObject(dis);
redisClient.SetString("newProd", json);
}
}
}
var data = redisClient.GetString("newProd");
ViewBag.Prod = JsonConvert.DeserializeObject(data);
//ViewBag.Result = db.StringGet("hash");
return View("Detils",listnew);
}
显示页面:Detils.cshtml
@{
ViewData["Title"] = "Detils";
}
<h1>购物车</h1>
<table class="table table-striped table-hover">
<tr>
<th>商品名称</th>
<th>商品数量</th>
<th>小计</th>
<th>操作</th>
</tr>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>@item.Name</td>
<td>@ViewBag.Prod[item.Name]</td>
<td>@string.Format("{0:C}元", item.Price * Convert.ToInt32(ViewBag.Prod[item.Name]))</td>
<td><a href="@Url.Action("Delete","Home",new { id=item.Id})" class="btn btn-primary btn-lg">删除</a></td>
</tr>
}
</tbody>
</table>