ASP.NET Core API+MVC+Redis 模擬購物車

2020-08-27 騎著小豬去拉薩




步驟:
1、打開vs2019創建項目,選擇asp.net core web 應用程式,選擇API,開始創建
2、點項目右鍵,在管理NuGet程序包選擇EF,添加


3、選擇vs工具的管理NuGet程序,在選擇程序包管理器控制臺
4、輸入:Scaffold-DbContext &39; Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Context ShopContext
這裡需要注意的是:ShoppingDB是資料庫的名稱, ShopContext是上下文
5、在appsettings.json添加&34;: {

&34;: &34;

},
6、在Startup.cs 文件裡面的public void ConfigureServices(IServiceCollection services)添加
services.AddDbContext<ShopContext>(options => { options.UseSqlServer(Configuration.GetConnectionString(&34;)); }); 注意:shopdb是appsettings.json裡面添加的shopdb 7、在Controllers文件夾添加控制器,選擇空的api,添加路由 [Route(&34;)]
注意,如果不加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(&34;)] [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(&34;); var result = await task; list = JsonConvert.DeserializeObject<IEnumerable<Products>>(result); return View(list); }

3、Index.cshtml 頁面如下:

@{ ViewData[&34;] = &34;;}<h1>商品列表</h1><table class=&34;> <tr> <th>商品名稱</th> <th>商品價格</th> <th>操作</th> </tr> <tbody> @foreach (var item in Model) { <tr> <td>@item.Name</td> <td>@string.Format(&34;, item.Price)</td> <td><a href=&34;Detils&34;Home&34; class=&34;>添加到購物車</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 = &34;, Configuration = &34; }; 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(&34;, json); } } } var data = redisClient.GetString(&34;); ViewBag.Prod = JsonConvert.DeserializeObject(data); //ViewBag.Result = db.StringGet(&34;); 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(&34;, json); } } } var data = redisClient.GetString(&34;); ViewBag.Prod = JsonConvert.DeserializeObject(data); //ViewBag.Result = db.StringGet(&34;); return View(&34;,listnew); }

顯示頁面:Detils.cshtml

@{ ViewData[&34;] = &34;;}<h1>購物車</h1><table class=&34;> <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(&34;, item.Price * Convert.ToInt32(ViewBag.Prod[item.Name]))</td> <td><a href=&34;Delete&34;Home&34; class=&34;>刪除</a></td> </tr> } </tbody></table>

相關焦點

  • ASP.NET CORE 版本的DTcms Core即將發布
    一直以來,作為DTcms的鐵桿粉絲,從DTcms 3.0到4.0,再從4.0到5.0,一直緊緊隨,如今DTcms 的.net core版本即將要發布了(我個人預計2020年10月份左右),真是非常期待!
  • Asp.net Core啟動流程講解(三)
    asp.net core其實內部依賴的是IStartup接口,至於Startup只是一個非IStartup硬性約束的實現 public interface IStartup { IServiceProvider ConfigureServices(IServiceCollection services); void Configure
  • Asp.net Core啟動流程講解(一)
    asp.net core默認項目包括項目根目錄級的Startup.cs、Program.csCore 3.0以及以後版本的替換依賴注入就得在Program內配置.net core 3.0之前的Program.cs.net core 3.0之後的Program.cs.net core 3.0之前的Program.cs
  • .net core 3.x 啟動順序
    1. .netcore 3.x啟動執行順序ConfigureWebHostDefaults:使用.net core 3.x的默認配置ConfigureHostConfigurationConfigureAppConfigurationConfigureServicesConfigureLogging
  • asp.net core 5.0 中的 JsonConsole
    asp.net core 5.0 中的 JsonConsoleIntroasp.net core 5.0 中日誌新增了 JsonConsole,還是輸出日誌到 Console,但是會應用 Json 格式的一個 Formatter 把日誌格式化成 json 再輸出到控制臺
  • asp .net core 中間件
    前言對中間件的一個概況,在《重新整理.net core 計1400篇》系列後面會深入。正文什麼是中間件呢?其實中間件這個概念來源於分布式,當然這是一個狹隘的概念了,現在中間件概念就非常廣泛了。官網給出了這樣一張圖,這張圖認為從請求到響應過程中間都是中間件,包括我們認為的路由。
  • 手把手教你ASP.NET Core:創建 Web API
    using Microsoft.AspNetCore.Mvc;using System.Collections.Generic;namespace Course001.Controllers{ [Route("api/[controller]")] [ApiController] public class TodosController
  • asp.net core 使用 TestServer 來做集成測試
    asp.net core 使用 TestServer 來做集成測試Intro之前我的項目裡的集成測試是隨機一個埠,每次都真實的啟動一個 WebServer,之前也有看到過微軟文檔上 TestServer 的介紹,當時沒仔細看過以為差不多就沒用,一直是啟動了一個真正的
  • ASP.NET Core項目目錄結構介紹
    我們下面通過在Visual Studio 2017中創建一個空的Web應用程式來詳細說明下asp.net core項目目錄結構:1、項目結構說明(1)、依賴項這裡主要分兩部分SDK, 目前這兩部分下面都只有一項。
  • 微軟推出 VS for Mac ASP.NET Core 挑戰
    (微軟打錢)詳情查看原博客:https://devblogs.microsoft.com/visualstudio/join-the-visual-studio-for-mac-asp-net-core-challenge
  • .net core面試題
    第1題,什麼是ASP net core?首先ASP net core不是 asp net的升級版本。它遵循了dot net的標準架構, 可以運行於多個作業系統上。它更快,更容易配置,更加模塊化,可擴展性更強。 第2題,asp dot core有哪些好的功能?第一是依賴注入。
  • 分享ASP.NET MVC 系統性能優化的一個實戰案例
    系統使用了Asp.net mvc+EntityFramework+WCF等相關技術,系統的部署,也做了負載均衡(一共有三臺應用伺服器)。隨著系統用戶量的增多,資料庫記錄數的劇增,系統經常出現一些卡頓問題,系統優化變得迫在眉睫。為了改變現狀,我細細的研究現有系統的源碼,提出了一些系統優化方案。
  • Asp.net Core啟動流程講解(二)
    asp.net core內,launchSettings.json提供給開發工具一些參數化,提供開發調試3、默認項目的profiles節點下包括 IIS Express 和 項目同名的節點,前者是Visual Studio的IIS Express調試參數,後者是命令行啟動.net core項目的配置參數可通過配置 profiles/節點
  • 不用虛機不用Docker使用Azure應用服務部署ASP.NET Core程序
    發布程序有了新建的.net訪問應用服務上面提到了新建資源的時候需要填寫名稱,這個名稱加上.azurewebsites.net就是服務對應的地址。讓我們訪問一下吧。可以看到我們的asp.net core應用程式發布成功了,示例代碼可以運行了。
  • 實戰Pure前端框架及ASP.NET MVC設計模式
    asp.net mvc43、Razor布局頁面
  • 打錢啦,微軟推出 VS for Mac ASP.NET Core 激勵挑戰
    (微軟打錢)詳情查看原博客:https://devblogs.microsoft.com/visualstudio/join-the-visual-studio-for-mac-asp-net-core-challenge
  • Asp.Net Core多榜逆襲,這是.NET最好的時代
    TechEmpowerTechEmpower第19輪程式語言框架性能排行榜2020年5月28日正式發布,詳見官方博客:https://www.techempower.com/blog/2020/05/28/framework-benchmarks-round-19/,asp.net
  • ASP.NET Core MVC中的兩種404錯誤
    </h5></div><a asp-controller="home" asp-action="index" class="btn btn-outline-success" style="width:auto">單擊此處查看學生信息列表</a>
  • 【asp.net core 實戰項目】電子商場——開始擼代碼,搭建框架
    文件操作類正式開始打開VS,新建一個asp.netcore 的web項目創建項目項目結構如下:項目結構新建完成之後,我們來看一下這幾個文件夾中應該存放對應的什麼文件:第一個 Core ,這個裡面,會放一些和項目相關的核心類第二個 Service ,這個裡面放一些處理處理實際業務邏輯的方法第三個 Cotrollers,Views,Models 是 多net
  • .net core 中的經典設計模式的應用
    &34;Kangkang&34;{context.RequesterName} {context.Hour}h apply failed&34;pass 1&34;pass 2&34;pass 3&34;--------- h:{i} apply Pipeline------------------&34;----------------------------&asp.net