创建NetCore2.2 Web项目+EFCore+SQLServer

在空余时间学习下NetCore,记录日常,供参考。

1.确保已下载安装NetCore2.2SDK 环境,下载地址:https://dotnet.microsoft.com/download/dotnet-core/2.2

2.打开VS2017,首先新建一个解决方案,并在解决方案上新建项目操作,选择ASP.NET Core Web 应用程序,点击“确定”。继续,NetCore版本选择ASP.NET Core 2.2,类型选择“Web应用程序”点击确定。

3、在appsettings.json添加配置数据库链接字符串,添加后如下图

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*",
"ConnectionStrings": { "DefaultConnectionString": "Data Source=.;Initial Catalog=bcmf_core;User ID=sa;Password=123456" } }

 4.NetCore2.2的SDK正常包含有Microsoft.EntityFrameworkCore和microsoft.EntityFrameworkCore.SqlServer,若没有,可以在NuGet包中查询安装,这里也是安装的2.2版本

NuGet官网:https://www.nuget.org/

搜索以上两个引用名称,获取安装命令行,在VS2017的程序包管理器控制台输入对应命令行,如下:

 

5.在Models文件夹新建文件夹“Entity”,在Entity下存放我们的数据实体类,新建实体类User.cs,这里视个人情况而定,我选择的是以前项目的一个测试数据库。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace NetCoreCMS.Models.Entity
{
    public class User
    {
        public int UserId { get; set; }
        public int PermissionId { get; set; }
        public int RoleId { get; set; }
        public string Name { get; set; }
        public string NameCN { get; set; }
        public string Email { get; set; }
        public string Password { get; set; }
        public bool IsSystem { get; set; }
        public bool IsActive { get; set; }
    }
  
    /// <summary>
    /// 返回模型类
    /// </summary>
  public class UserViewModel
    {
        public int UserId { get; set; }
        public int PermissionId { get; set; }
        public int RoleId { get; set; }
        public string Name { get; set; }
        public string NameCN { get; set; }
        public string Email { get; set; }
        public string IsSystem { get; set; }
        public string IsActive { get; set; }
    }
}

5、在Models文件夹新建文件夹“Mapping”,在Mapping下存放我们的数据实体映射类,新建实体类UserMapping.cs,

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using CMSCore.Web.Models.Entity;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

namespace CMSCore.Web.Models.Mapping
{
    public class UserMapping : IEntityTypeConfiguration<User>
    {
        void IEntityTypeConfiguration<User>.Configure(EntityTypeBuilder<User> builder)
        {
            builder.ToTable("User");//对应数据库User表
            builder.HasKey("UserId");
            builder.Property(t => t.PermissionId).HasColumnName("PermissionId").IsRequired();
            builder.Property(t => t.RoleId).HasColumnName("RoleId").IsRequired();
            builder.Property(t => t.Name).HasColumnName("Name").IsRequired().HasMaxLength(50);
            builder.Property(t => t.NameCN).HasColumnName("NameCN").IsRequired().HasMaxLength(50);
            builder.Property(t => t.Email).HasColumnName("Email").IsRequired().HasMaxLength(50);
            builder.Property(t => t.Password).HasColumnName("Password").IsRequired();
            builder.Property(t => t.IsSystem).HasColumnName("IsSystem").IsRequired();
            builder.Property(t => t.IsActive).HasColumnName("IsActive").IsRequired();
        }
    }
}

6、在Models文件夹新建上下文BcmfContext.cs类

using CMSCore.Web.Models.Entity;
using CMSCore.Web.Models.Mapping;
using Microsoft.EntityFrameworkCore;

namespace CMSCore.Web.Models
{
    public class BcmfDBContext : DbContext
    {
        public BcmfDBContext(DbContextOptions options) : base(options)
        {
        }
     
        public DbSet<User> User { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.ApplyConfiguration(new UserMapping()); base.OnModelCreating(modelBuilder); } } }

7、在入口文件注册上下文,在根目录Startup.cs的ConfigureServices方法中,注册上下文。

不要忘记了添加引用命名空间
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.SqlServer;

 // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            //注册数据库操作上下文
            services.AddDbContext<BcmfDBContext>(option => option.UseSqlServer(Configuration.GetConnectionString("DefaultConnectionString")));
        }

8、在Controller文件夹下,创建控制器UserController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using CMSCore.Web.Models;
using CMSCore.Web.Models.Entity;
using Microsoft.AspNetCore.Mvc;

// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace CMSCore.Web.Controllers
{
    public class UserController : Controller
    {
        private readonly BcmfDBContext db;

        public UserController(BcmfDBContext _db)
        {
            db = _db;
        }

        // GET: /<controller>/
        public IActionResult Index()
        {
            var userList = db.User.Where(m => m.IsActive).Select(t => new UserViewModel
            {
                Email = t.Email,
                IsActive = t.IsActive ? "激活" : "禁用",
                IsSystem = t.IsSystem ? "" : "",
                Name = t.Name,
                NameCN = t.NameCN,
                PermissionId = t.PermissionId,
                RoleId = t.RoleId,
                UserId = t.UserId
            });
            return Json(userList);
        }
    }
}

运行、访问/user/index,成功获取用户信息

转载于:https://www.cnblogs.com/luckypc/p/10790924.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Netcore6.0是微软推出的全新版本的开发框架,它提供了强大且灵活的功能,用于构建Web应用程序和API。Web API是Netcore6.0中的一项重要功能,它允许我们构建基于HTTP协议的API,并通过JSON格式进行数据交换。 JWT(JSON Web Token)是一种用于在网络应用间传递信息的安全方法。在Netcore6.0中,我们可以使用JWT来实现Web API的授权功能。JWT由三部分组成:头部、载荷和签名。头部包含了令牌的类型和算法,载荷包含了我们想要传递的数据,签名通过使用密钥进行加密来验证令牌的合法性。 在Netcore6.0中,我们可以使用Microsoft提供的Microsoft.AspNetCore.Authentication.JwtBearer包来简单地实现JWT的授权功能。首先,我们需要在Startup.cs文件的ConfigureServices方法中配置JWT的身份验证服务,并指定密钥、颁发者、验证等参数。然后,在Configure方法中启用身份验证中间件和JWT授权中间件。 在Vue3中,我们可以使用Axios库来发送HTTP请求并附带JWT令牌进行授权。Vue3是一种流行的JavaScript框架,用于构建现代化的用户界面。通过Axios,我们可以将JWT令牌添加到请求的Authorization头部中,并在后端接收到请求时进行验证。 为了实现Vue3与Netcore6.0的JWT授权,我们首先需要在Vue3项目中安装Axios库,并配置请求拦截器,在每个请求发送前将JWT令牌添加到请求头中。后端接收到带有JWT令牌的请求后,使用相同的密钥和算法进行解密并验证令牌的合法性。 综上所述,Netcore6.0的Web API和Vue3的JWT授权组合,可以实现安全可靠的API授权。通过合理的配置和使用,我们可以保护API免受未经授权的访问,并确保只有经过身份验证的用户才能访问敏感数据或执行特定操作。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值