.net Core 2.1 MVC+EF+Redis搭建
阿新 • • 發佈:2018-08-03
文件 dds cookie exception reg direct mvc+ef microsoft encoding
官方學習資料
搭建空MVC框架
1.創建一個空模板
2.創建文件夾 Controllers、Models、Views
3.在Controllers文件夾下創建HomeController.cs
選擇Controllers文件夾,右鍵-添加-新建項,選擇MVC控制器類,添加HomeController.cs。
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http;using Microsoft.AspNetCore.Mvc; namespace RazorMvc.Controllers { public class HomeController : Controller { // GET: Home public ActionResult Index() { return View(); } } }
4.在Models文件夾下創建HomeModel.cs
using System; using System.Collections.Generic;using System.Linq; using System.Threading.Tasks; namespace RazorMvc.Models { public class HomeModel { } }
5.在Views文件夾中添加_Layout.cshtml
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>@ViewData["Title"]</title> </head> <body> @RenderBody() @RenderSection("Scripts", false) </body> </html>
6.在Views文件夾中添加_ViewStart.cshtml
@{ Layout = "~/Views/_Layout.cshtml"; }
7.在Views文件夾中添加_ViewImports.cshtml
@using 項目命名空間
@using 項目命名空間.Models
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
8.調整Startup.cs
public void ConfigureServices(IServiceCollection services) { services.AddMvc();//註冊服務 } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseCookiePolicy(); app.UseSession(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); }
9.調整完成後可保存為模板(可跳過,等後面完事一起存)
EF Core搭建
1.安裝 EF Core
- 工具 > NuGet 包管理器 > 包管理器控制臺
- 運行
Install-Package Microsoft.EntityFrameworkCore.SqlServer
- 運行
Install-Package Microsoft.EntityFrameworkCore.Tools
- 運行
Install-Package Microsoft.VisualStudio.Web.CodeGeneration.Design
- 聽話全安了
2.從現有數據庫創建模型
Scaffold-DbContext"Server=.;Database=test;uid=test;pwd=test;"Microsoft.EntityFrameworkCore.SqlServer-OutputDirModels
可以通過將-Tables
參數添加到上述命令來指定要為哪些表生成實體。 例如-Tables Blog,Post
。
3.刪除內聯上下文配置
- 打開
Models\BloggingContext.cs
- 刪除
OnConfiguring(...)
方法
4.在 Startup.cs 中註冊並配置上下文
public void ConfigureServices(IServiceCollection services) { services.AddMvc(); var connection = @"Server=.;Database=test;uid=test;pwd=test;"; services.AddDbContext<testContext>(options => options.UseSqlServer(connection)); }
5.系統生成測試頁面
- 在“解決方案資源管理器”中,右鍵單擊“控制器”文件夾,然後選擇“添加”->“控制器…”
- 選擇“視圖使用 Entity Framework 的 MVC 控制器”,然後單擊“確定”
- 將“模型類”設置為“Test”,將“數據上下文類”設置為“TestContext”
- 單擊“添加”
- 可運行起來測試數據庫連接
使用Redis存儲Session
//根據自己需要修改配置文件,此處直接https://www.cnblogs.com/shouwu/p/6180652.html,
1.添加nuget程序包
Microsoft.AspNetCore.Session; Microsoft.AspNetCore.DataProtection.Redis; Microsoft.Extensions.Caching.Redis.Core; Microsoft.AspNetCore.Http; //使用Session時有擴展方法
2.在appsettings.json中添加Redis配置
{ "Logging": { "LogLevel": { "Default": "Warning" } }, "AllowedHosts": "*", "WebConfig": { "Redis": { "Connection": "ip:6379,allowAdmin=true,password=Test", "InstanceName": "名稱" }, "SessionTimeOut": "30" } }
3.在startup.cs類中,按如下例子添加代碼
public IConfiguration Configuration { get; } public Startup(IConfiguration configuration) { Configuration = configuration; }
ConfigureServices() 增加
#region 使用Redis保存Session var redisConn = Configuration["WebConfig:Redis:Connection"]; var redisInstanceName = Configuration["WebConfig:Redis:InstanceName"]; //Session 過期時長分鐘 var sessionOutTime = Configuration.GetValue<int>("WebConfig:SessionTimeOut", 30); var redis = StackExchange.Redis.ConnectionMultiplexer.Connect(redisConn); services.AddDataProtection().PersistKeysToRedis(redis, "DataProtection-Test-Keys"); services.AddDistributedRedisCache(option => { //redis 連接字符串 option.Configuration = redisConn; //redis 實例名 option.InstanceName = redisInstanceName; }); #endregion //添加Session並設置過期時長 services.AddSession(options => { options.IdleTimeout = TimeSpan.FromMinutes(sessionOutTime); });
Configure() 在app.UseMvc之前增加
app.UseSession();
Redis存儲Session
HttpContext.Session.SetString("UserName", userName); HttpContext.Session.GetString("UserName");
普通存儲Redis
public IDistributedCache _RCache { get; set; } public MyToolController(IDistributedCache RCache) { _RCache = RCache; } _RCache.SetString("UserName", UserName); _RCache.GetString("UserName");
附加
- JS/CSS 壓縮
Install-Package YUICompressor.NET
- JS壓縮
JavaScriptCompressor jsCompressor = new JavaScriptCompressor { //使用utf-8 編碼文件 Encoding = Encoding.UTF8 }; jsCompressor.Compress(str);
- Css壓縮
CssCompressor cssCompressor = new CssCompressor(); cssCompressor.Compress(str);
- 安裝結束後包數量,無任何參考價值hhh
.net Core 2.1 MVC+EF+Redis搭建