標籤:alt model end 沒有 asp.net null target 輸入 studio
註:本文提到的程式碼範例> https://code.msdn.microsoft.com/How-to-use-Redis-in-ASPNET-0d826418
Redis 是一個開源的記憶體中的資料結構儲存系統,可以用作資料庫、緩衝和訊息中介軟體。它支援多種類型的資料結構:字串,雜湊表,列表,集合,有序集等等。
Redis 官方沒有推出Windows版本,倒是由Microsoft Open Tech提供了Windows 64bit 版本支援。
如何在Windows機器上安裝Redis=>下載安裝檔案Redis-x64-3.2.100.msi,安裝完畢之後,開啟service管理器,找到Redis服務,並將其啟動。
前期準備:
1.推薦使用Visual Studio 2015 Update3作為你的IDE,:www.visualstudio.com
2.你需要安裝.NET Core的運行環境以及開發工具,這裡提供VS版:www.microsoft.com/net/core
建立項目:
開啟VS 2015,建立->項目->C#模板->Web->ASP.NET Core Web Application(.NET Core)
選擇好路徑,項目名為CSCoreRedis,確定後選擇Web Application,身分識別驗證選擇無。
項目建立完之後,在CSCoreRedis項目上右鍵選擇管理NuGet包,搜尋StackExchange.Redis並安裝。
我們將用這個庫提供的介面去操作Redis。
代碼:
首先要在HomeController.cs中添加Redis的串連,如果你不是用的本地Redis服務,請自行修改連接字串。
private static Lazy<ConnectionMultiplexer> lazyConnection = new Lazy<ConnectionMultiplexer>(() =>{ return ConnectionMultiplexer.Connect("localhost,abortConnect=false");});public static ConnectionMultiplexer Connection{ get { return lazyConnection.Value; }}
添加建構函式,初始化database和List。這裡使用ListLeftPush是為了在後面用ListRange的時候從左至右取能取到最新的資料。
public static string ListKeyName = "MessageList";public HomeController(){ db = Connection.GetDatabase(); if (db.IsConnected(ListKeyName) && (!db.KeyExists(ListKeyName) || !db.KeyType(ListKeyName).Equals(RedisType.List))) { //Add sample data. db.KeyDelete(ListKeyName); //Push data from the left db.ListLeftPush(ListKeyName, "TestMsg1"); db.ListLeftPush(ListKeyName, "TestMsg2"); db.ListLeftPush(ListKeyName, "TestMsg3"); db.ListLeftPush(ListKeyName, "TestMsg4"); }}
修改Index.cshtml檔案,添加輸入框及按鈕
<form action="/Home/SendMessage" method="post"> <input type="text" name="message" style="width:250px" /> <input name="btnSend" value="Send" type="submit" style="margin-left:5px" /></form>
在controller中添加SendMessage方法
[HttpPost]public ActionResult SendMessage(string message){ if (db.IsConnected(ListKeyName)) { db.ListLeftPush(ListKeyName, message); } return RedirectToAction("Index");}
顯示錯誤資訊或資訊列表
@if (@ViewData["Error"] != null){ <h2>@ViewData["Error"]</h2>}else{ <div id="MessageList"> <h3>Latest messages</h3> @foreach (var msg in Model) { <div>@Html.DisplayFor(modelItem => msg) </div> } </div> }
我們來看一下運行結果
在輸入框中輸入字元,按下Send按鈕,頁面上將會顯示最新的5條資訊。
下載完整的代碼,請訪問 https://code.msdn.microsoft.com/How-to-use-Redis-in-ASPNET-0d826418
要瞭解更多關於Redis的資訊,請訪問Redis官方網站http://www.redis.io/
關於StackExchange.Redis的詳細文檔,請訪問https://github.com/StackExchange/StackExchange.Redis
如需瞭解微軟Azure Redis 緩衝,請訪問https://azure.microsoft.com/zh-cn/services/cache/
如何在ASP.NET Core中使用Redis