Asp.Net Core WebApi Swagger+Autofac+JWT的實現(一)

 開發環境:VS2017、.Net core 2.1、SQLServer數據庫

首先,先將項目的基礎框架搭建起來,項目使用的是Core EF DBFirst機制,DDD模式

本章實現一下項目框架的基礎搭建

1、使用 VS2017創建一個 .net core 的webapi項目,項目創建完成後,在項目中添加相關的業務類庫,類庫都爲.net core 類庫

NetCore.App:數據業務層

NetCore.Infrastructure:通用方法

NetCore.Repository:Model實體以及數據庫

NetCore.WebApi:webapi 接口

2、NetCore.Repository的搭建

Nuget添加 Microsoft.EntityFrameworkCore.SqlServer、Z.EntityFramework.Plus.EFCore兩個包的引用

Common:通用實體類

Domain:數據庫表實體類

RequestEntity:WebApi請求參數實體類

ResponseEntity:WebApi返回數據實體類

NetCoreDbContext:數據庫上下文

BaseRepository:數據庫操作通用方法

UnitWork:數據庫事務操作方法

NetCoreDbContext代碼

using System;
using Microsoft.EntityFrameworkCore;
using NetCore.Repository.Domain;

namespace NetCore.Repository
{
    public class NetCoreDbContext:DbContext
    {
        public NetCoreDbContext(DbContextOptions<NetCoreDbContext> options):base(options)
        {

        }
        #region dbSet
        public virtual DbSet<UserInfo> UserInfos { get; set; }
        #endregion
    }
}

BaseRepository代碼

using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Linq.Expressions;
using NetCore.Repository.Domain;
using Microsoft.EntityFrameworkCore;
using Z.EntityFramework.Plus;

namespace NetCore.Repository
{
    /// <summary>
    /// 數據操作通用方法
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class BaseRepository<T> where T : BaseModel
    {
        protected NetCoreDbContext netCoreDbContext;

        public BaseRepository(NetCoreDbContext _netCoreDbContext)
        {
            netCoreDbContext = _netCoreDbContext;
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public  bool Add(T entity)
        {
            try
            {
                //netCoreDbContext.Set<T>().Add(entity);
                //netCoreDbContext.SaveChanges();
                //netCoreDbContext.Entry(entity).State = EntityState.Detached;
                netCoreDbContext.Entry(entity).State = EntityState.Added;
                int rowsAffected = netCoreDbContext.SaveChanges();
                return rowsAffected > 0 ? true : false;
            }
            catch(Exception ex)
            {
                return false;
            }
        }

        /// <summary>
        /// 批量添加
        /// </summary>
        /// <param name="entities"></param>
        /// <returns></returns>
        public bool BatchAdd(T[] entities)
        {
            try
            {
                netCoreDbContext.Set<T>().AddRange(entities);
                int rowsAffected = netCoreDbContext.SaveChanges();
                return rowsAffected == entities.Length ? true : false;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public bool Update(T entity)
        {
            try
            {
                netCoreDbContext.Set<T>().Attach(entity);
                netCoreDbContext.Entry(entity).State = EntityState.Modified;
                int rowsAffected = netCoreDbContext.SaveChanges();
                return rowsAffected > 0 ? true : false;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        /// <summary>
        /// 根據條件更新數據
        /// <para>如:Update(u =>u.Id==1,u =>new User{Name="ok"});</para>
        /// </summary>
        /// <param name="where">The where.</param>
        /// <param name="entity">The entity.</param>
        public bool Update(Expression<Func<T, bool>> where, Expression<Func<T, T>> entity)
        {
            try
            {
                netCoreDbContext.Set<T>().Where(where).Update(entity);
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        /// <summary>
        /// 根據ID獲取單個數據
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public T GetEntiyByID(Guid id)
        {
            try
            {
                Expression<Func<T, bool>> where = x => x.ID.Equals(id);
                var modelList = netCoreDbContext.Set<T>().Where(where).AsQueryable().ToList();
                return modelList.Any() ? modelList.FirstOrDefault() : null;
            }
            catch (Exception ex)
            {
                return null;
            }
        }
        /// <summary>
        /// 根據查詢條件獲取單個數據
        /// </summary>
        /// <param name="expression"></param>
        /// <returns></returns>
        public T GetEntityByWhere(Expression<Func<T,bool>> expression)
        {
            return netCoreDbContext.Set<T>().FirstOrDefault(expression);
        }
        /// <summary>
        /// 根據ID刪除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool Delete(Guid id)
        {
            var model = GetEntiyByID(id);
            if (model != null)
            {
                try
                {
                    netCoreDbContext.Set<T>().Attach(model);
                    netCoreDbContext.Entry(model).State = EntityState.Deleted;
                    int rowsAffected = netCoreDbContext.SaveChanges();
                    return rowsAffected > 0 ? true : false;
                }
                catch (Exception ex)
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// 刪除
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public bool Delete(T entity)
        {
            try
            {
                netCoreDbContext.Set<T>().Remove(entity);
                int rowsAffected = netCoreDbContext.SaveChanges();
                return rowsAffected > 0 ? true : false;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        /// <summary>
        /// 根據條件刪除數據
        /// </summary>
        /// <param name="expression"></param>
        public bool Delete(Expression<Func<T, bool>> expression)
        {
            try
            {
                netCoreDbContext.Set<T>().Where(expression).Delete();
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        /// <summary>
        /// 判斷數據是否存在
        /// </summary>
        /// <param name="expression"></param>
        /// <returns></returns>
        public bool IsExist(Expression<Func<T,bool>> expression)
        {
            return netCoreDbContext.Set<T>().Any(expression);
        }

        /// <summary>
        /// 獲取數據列表
        /// </summary>
        /// <param name="orderExp">排序條件</param>
        /// <param name="expression">查詢條件</param>
        /// <param name="orderBy">排序方式</param>
        /// <returns></returns>
        public List<T> GetList(Expression<Func<T, dynamic>> orderExp,Expression<Func<T,bool>> expression = null,string orderBy="desc")
        {
            try
            {
                IQueryable<T> quary;
                if (expression != null)
                {
                    quary= netCoreDbContext.Set<T>().AsNoTracking().AsQueryable();
                }
                else
                {
                    quary= netCoreDbContext.Set<T>().AsNoTracking().AsQueryable().Where(expression);
                }
                return orderBy == "desc" ? quary.OrderByDescending(orderExp).ToList() : quary.OrderBy(orderExp).ToList();
            }
            catch (Exception ex)
            {
                return null;
            }
        }
        /// <summary>
        /// 獲取分頁數據列表
        /// </summary>
        /// <param name="expression">查詢條件</param>
        /// <param name="pageSize">每頁條數</param>
        /// <param name="pageIndex">頁碼</param>
        /// <param name="orderExp">排序條件</param>
        /// <param name="orderBy">排序方式</param>
        /// <param name=""></param>
        /// <returns></returns>
        public List<T> GetPageList(Expression<Func<T, bool>> expression,int pageSize,int pageIndex,out int totalCount, Expression<Func<T, dynamic>> orderExp, string orderBy = "desc")
        {
            try
            {
                if (pageIndex < 1)
                {
                    pageIndex = 1;
                }
                int skipCount = (pageIndex - 1) * pageSize;
                totalCount = netCoreDbContext.Set<T>().Where(expression).Count();
                IQueryable<T> quary = netCoreDbContext.Set<T>().AsNoTracking().AsQueryable().Where(expression);
                return orderBy == "desc" ? quary.OrderByDescending(orderExp).Skip(skipCount).Take(pageSize).ToList() : quary.OrderBy(orderExp).Skip(skipCount).Take(pageSize).ToList();
            }
            catch (Exception ex)
            {
                totalCount = 0;
                return null;
            }
        }
    }
}

UnitWrok代碼

using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Linq.Expressions;
using NetCore.Repository.Domain;
using Microsoft.EntityFrameworkCore;
using Z.EntityFramework.Plus;

namespace NetCore.Repository
{
    /// <summary>
    /// 數據庫事務操作方法
    /// </summary>
    public class UnitWork
    {
        protected NetCoreDbContext netCoreDbContext;

        public UnitWork(NetCoreDbContext _netCoreDbContext)
        {
            netCoreDbContext = _netCoreDbContext;
        }
        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public bool Add<T>(T entity) where T:BaseModel
        {
            try
            {
                //netCoreDbContext.Set<T>().Add(entity);
                //netCoreDbContext.SaveChanges();
                //netCoreDbContext.Entry(entity).State = EntityState.Detached;
                netCoreDbContext.Entry(entity).State = EntityState.Added;
                int rowsAffected = netCoreDbContext.SaveChanges();
                return rowsAffected > 0 ? true : false;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        /// <summary>
        /// 批量添加
        /// </summary>
        /// <param name="entities"></param>
        /// <returns></returns>
        public bool BatchAdd<T>(T[] entities) where T:BaseModel
        {
            try
            {
                netCoreDbContext.Set<T>().AddRange(entities);
                int rowsAffected = netCoreDbContext.SaveChanges();
                return rowsAffected == entities.Length ? true : false;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public bool Update<T>(T entity) where T:class
        {
            try
            {
                netCoreDbContext.Set<T>().Attach(entity);
                netCoreDbContext.Entry(entity).State = EntityState.Modified;
                int rowsAffected = netCoreDbContext.SaveChanges();
                return rowsAffected > 0 ? true : false;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        /// <summary>
        /// 根據條件更新數據
        /// <para>如:Update(u =>u.Id==1,u =>new User{Name="ok"});</para>
        /// </summary>
        /// <param name="where">The where.</param>
        /// <param name="entity">The entity.</param>
        public bool Update<T>(Expression<Func<T, bool>> where, Expression<Func<T, T>> entity)where T:class
        {
            try
            {
                netCoreDbContext.Set<T>().Where(where).Update(entity);
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        /// <summary>
        /// 根據ID獲取單個數據
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public T GetEntiyByID<T>(Guid id) where T:BaseModel
        {
            try
            {
                Expression<Func<T, bool>> where = x => x.ID.Equals(id);
                var modelList = netCoreDbContext.Set<T>().Where(where).AsQueryable().ToList();
                return modelList.Any() ? modelList.FirstOrDefault() : null;
            }
            catch (Exception ex)
            {
                return null;
            }
        }
        /// <summary>
        /// 根據查詢條件獲取單個數據
        /// </summary>
        /// <param name="expression"></param>
        /// <returns></returns>
        public T GetEntityByWhere<T>(Expression<Func<T, bool>> expression) where T:class
        {
            return netCoreDbContext.Set<T>().FirstOrDefault(expression);
        }

        /// <summary>
        /// 刪除
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public bool Delete<T>(T entity) where T:class
        {
            try
            {
                netCoreDbContext.Set<T>().Remove(entity);
                int rowsAffected = netCoreDbContext.SaveChanges();
                return rowsAffected > 0 ? true : false;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        /// <summary>
        /// 根據條件刪除數據
        /// </summary>
        /// <param name="expression"></param>
        public bool Delete<T>(Expression<Func<T, bool>> expression) where T:class
        {
            try
            {
                netCoreDbContext.Set<T>().Where(expression).Delete();
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        /// <summary>
        /// 判斷數據是否存在
        /// </summary>
        /// <param name="expression"></param>
        /// <returns></returns>
        public bool IsExist<T>(Expression<Func<T, bool>> expression) where T:class
        {
            return netCoreDbContext.Set<T>().Any(expression);
        }

        /// <summary>
        /// 獲取數據列表
        /// </summary>
        /// <param name="orderExp">排序條件</param>
        /// <param name="expression">查詢條件</param>
        /// <param name="orderBy">排序方式</param>
        /// <returns></returns>
        public List<T> GetList<T>(Expression<Func<T, dynamic>> orderExp,Expression<Func<T, bool>> expression = null,string orderBy="desc") where T:class
        {
            try
            {
                IQueryable<T> quary;
                if (expression != null)
                {
                    quary = netCoreDbContext.Set<T>().AsNoTracking().AsQueryable();
                }
                else
                {
                    quary= netCoreDbContext.Set<T>().AsNoTracking().AsQueryable().Where(expression);
                }
                return orderBy == "desc"?quary.OrderByDescending(orderExp).ToList():quary.OrderBy(orderExp).ToList();
            }
            catch (Exception ex)
            {
                return null;
            }
        }
        /// <summary>
        /// 獲取分頁數據列表
        /// </summary>
        /// <param name="expression">查詢條件</param>
        /// <param name="pageSize">每頁條數</param>
        /// <param name="pageIndex">頁碼</param>
        /// <param name="orderExp">排序條件</param>
        /// <param name="orderBy">排序方式</param>
        /// <param name=""></param>
        /// <returns></returns>
        public List<T> GetPageList<T>(Expression<Func<T, bool>> expression, int pageSize, int pageIndex, out int totalCount, Expression<Func<T, dynamic>> orderExp, string orderBy = "desc") where T:class
        {
            try
            {
                if (pageIndex < 1)
                {
                    pageIndex = 1;
                }
                int skipCount = (pageIndex - 1) * pageSize;
                totalCount = netCoreDbContext.Set<T>().Where(expression).Count();
                IQueryable<T> quary = netCoreDbContext.Set<T>().AsNoTracking().AsQueryable().Where(expression);
                return orderBy == "desc" ? quary.OrderByDescending(orderExp).Skip(skipCount).Take(pageSize).ToList() : quary.OrderBy(orderExp).Skip(skipCount).Take(pageSize).ToList();
            }
            catch (Exception ex)
            {
                totalCount = 0;
                return null;
            }
        }
    }
}

在Domain下添加BaseModel和UserInfo實體類

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;

namespace NetCore.Repository.Domain
{
    /// <summary>
    /// 通用字段實體類
    /// </summary>
    public abstract class BaseModel
    {
        /// <summary>
        /// 主鍵
        /// </summary>
        [Key]
        public string ID { get; set; } = Guid.NewGuid().ToString();
        /// <summary>
        /// 創建人
        /// </summary>
        [Required,StringLength(50)]
        public string CreateUser { get; set; }
        /// <summary>
        /// 創建時間
        /// </summary>
        public DateTime CreateTime { get; set; } = DateTime.Now;
        /// <summary>
        /// 修改人
        /// </summary>
        public string ModifyUser { get; set; }
        /// <summary>
        /// 修改日期
        /// </summary>
        public DateTime? ModifyTime { get; set; }
    }
}
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text;

namespace NetCore.Repository.Domain
{
    /// <summary>
    /// 用戶信息表
    /// </summary>
    [Table("UserInfo")]
    public class UserInfo:BaseModel
    {
        /// <summary>
        /// 用戶名
        /// </summary>
        public string UserName { get; set; }
        /// <summary>
        /// 登錄名
        /// </summary>
        public string LoginAccount { get; set; }
        /// <summary>
        /// 登錄密碼
        /// </summary>
        public string LoginPassword { get; set; }
    }
}

在WebApi中的appsettings中配置數據庫連接,添加ConnectionStrings

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "NetCoreDBContext": "Data Source=.;Initial Catalog=NetCoreWebApi;User=sa;Password=123456"
  }
}

在WebApi的Startup.cs中的ConfigureServices設置數據庫的連接

services.AddDbContext<NetCoreDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("NetCoreDBContext")));//獲取數據庫連接

3、NetCore.App的搭建

項目添加對NetCore.Repository及NetCore.Infrastructure兩個項目的引用

在項目中添加BaseApp、UserInfoApp兩個業務操作類

using System;
using System.Collections.Generic;
using System.Text;
using NetCore.Repository;
using NetCore.Repository.Domain;

namespace NetCore.App
{
    public class BaseApp<T> where T:BaseModel
    {
        protected UnitWork unitWork;
        protected BaseRepository<T> baseRepository;
        public BaseApp(UnitWork _unitWork, BaseRepository<T> _baseRepository)
        {
            unitWork = _unitWork;
            baseRepository = _baseRepository;
        }
    }
}
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq.Expressions;
using NetCore.Repository;
using NetCore.Repository.Domain;
using NetCore.Repository.RequestEntity;
using NetCore.Infrastructure;

namespace NetCore.App
{
    /// <summary>
    /// 用戶信息
    /// </summary>
    public class UserInfoApp:BaseApp<UserInfo>
    {
        public UserInfoApp(UnitWork unitWork,BaseRepository<UserInfo> baseRepository):base(unitWork,baseRepository)
        {

        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public bool Add(UserInfo userInfo)
        {
            return baseRepository.Add(userInfo);
        }
        /// <summary>
        /// 判斷賬戶是否已存在
        /// </summary>
        /// <param name="loginAccount"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool IsExist(string loginAccount,string id)
        {
            return baseRepository.IsExist(x => x.LoginAccount.Equals(loginAccount) && !x.ID.Equals(id));
        }
        /// <summary>
        /// 登錄
        /// </summary>
        /// <param name="loginAccount">登錄名</param>
        /// <param name="password">登錄密碼</param>
        /// <returns></returns>
        public UserInfo Login(string loginAccount,string password)
        {
            return baseRepository.GetEntityByWhere(x=>x.LoginAccount.Equals(loginAccount)&&x.LoginPassword.Equals(password));
        }

        /// <summary>
        /// 獲取用戶信息
        /// </summary>
        /// <param name="userInfoRequest"></param>
        /// <returns></returns>
        public List<UserInfo> GetList( UserInfoRequest userInfoRequest)
        {
            Expression<Func<UserInfo,bool>> predicte=x=>true;//查詢條件
            if (!string.IsNullOrEmpty(userInfoRequest.UserName))
            {
                predicte = predicte.And(x=>x.UserName.Contains(userInfoRequest.UserName));
            }
            Expression<Func<UserInfo, dynamic>> predicteSort = x =>x.CreateTime;//排序字段
            return baseRepository.GetList(predicteSort, predicte);
        }
    }
}

RequestEntity添加用戶查詢條件的實體

using System;
using System.Collections.Generic;
using System.Text;

namespace NetCore.Repository.RequestEntity
{
    /// <summary>
    /// 用戶查詢信息
    /// </summary>
    public class UserInfoRequest
    {
        /// <summary>
        /// 用戶名
        /// </summary>
        public string UserName { get; set; }
        /// <summary>
        /// 登錄名
        /// </summary>
        public string LoginAccount { get; set; }
        /// <summary>
        /// 登錄密碼
        /// </summary>
        public string LoginPassword { get; set; }
    }
}

完整代碼下載地址:https://download.csdn.net/download/liwan09/11717224

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章