.net Core 2.1 MVC+EF+Redis搭建

官方学习资料

搭建空MVC框架

1.创建一个空模板

image.png

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时有扩展方法

 Install-Package Microsoft.Extensions.Configuration
  Install-Package Microsoft.Extensions.Configuration.Json


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
    image.png
posted @ 2018-08-03 15:39  徐淳  阅读(465)  评论(0编辑  收藏  举报