经过一段时间的准备,新的一期【ASP.NET Core MVC开发实战之商城系统】已经开始,今天着重讲解布局设计,环境搭建,系统配置,及首页商品类型,banner条,友情链接等功能的开发。
首页是商城系统的门面,首页的设计的好坏关系着用户的体验,在本示例中,首页主要分为以下几个模块,如下所示:
所谓“工欲善其事必先利其器”,在开发程序之前,先将项目配置好。项目需要安装的第三方库,可通过Nuget包管理器进行安装。
目前程序用到的第三方库有三个:
具体安装库和版本如下所示:
汽配启动配置主要配置注入服务,及路由,主要有以下几个:
具体配置【Program.cs】参照如下所示:
using EasyBuyShop.DAL;
using EasyBuyShop.Utils;
using Microsoft.AspNetCore.Authentication.Cookies;
using NLog.Web;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
//1. 往容器中添加Session服务,启用Session服务
builder.Services.AddSession(option =>
{
option.IdleTimeout = TimeSpan.FromMinutes(10);
option.Cookie.Name = "DemoMvcCore";
});
//添加鉴权服务
builder.Services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
}).AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
{
options.LoginPath = "/Auth/Login";
options.LogoutPath = "/Auth/Logout";
});
// NLog: Setup NLog for Dependency injection
builder.Logging.ClearProviders();
builder.Host.UseNLog();
LogHelper.LoadConfiguration();
var app = builder.Build();
//启动时获取数据库连接字符串
BaseDal.ConnStr = app.Configuration.GetConnectionString("Default");
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
//2.使用Session中间件,主要用于拦截Http请求
app.UseSession();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
配置文件【appsetting.json】主要配置数据库连接字符串,及其他信息。如下所示:
{
"ConnectionStrings": {
"Default": "Server=localhost;Database=EasyBuyShop;Trusted_Connection=True;User Id=sa;Password=abc123"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
日志配置【nlog.config】主要配置NLog组件需要的日志保存路径以及层级等信息。如下所示:
注意:NLog日志组件不支持相对路径配置,如果想让日志保存在程序根目录,需要通过${basedir}进行配置,否则日志如法保存。
其中Header,Footer,前台各个页面都会用到,所以采用Layout布局页面展示【_Layout.cshtml】。如下所示:
@ViewData["Title"] - 易购商城
@if (!string.IsNullOrEmpty(ViewBag.UserName))
{
@ViewBag.RealName
}
else
{
亲,请登录
}
@RenderBody()
@await RenderSectionAsync("Scripts", required: false)
布局页面效果如下所示:
页头【Header】包含一个Form表单,用于查询商品信息,如下所示:
页脚【Footer】用于设置版权信息,如下所示:
首先每一个商品有类型,类型分为大类【Category】,中类,小类【SubCategory】,细类等,本文为了简化,只分为大类,小类两种。
数据表结构设计如下:
大类Category表,如下所示:
建表语句如下所示:
CREATE TABLE [dbo].[EB_Category](
[Id] [bigint] IDENTITY(1,1) NOT NULL,
[Category] [varchar](100) NULL,
[Description] [varchar](500) NULL,
[CreateTime] [datetime] NULL,
[CreateUser] [varchar](50) NULL,
[LastEditTime] [datetime] NULL,
[LastEditUser] [varchar](50) NULL
) ON [PRIMARY]
小类SubCategory表,如下所示:
注意:数据表中的分类内容,是从某宝抄下来的,然后整理好后,导入数据库。
建表语句如下所示:
CREATE TABLE [dbo].[EB_SubCategory](
[Id] [bigint] IDENTITY(1,1) NOT NULL,
[CategoryId] [bigint] NULL,
[SubCategory] [varchar](100) NULL,
[Description] [varchar](500) NULL,
[CreateTime] [datetime] NULL,
[CreateUser] [varchar](50) NULL,
[LastEditTime] [datetime] NULL,
[LastEditUser] [varchar](50) NULL
) ON [PRIMARY]
SqlSurgar采用模型对象映射ORM操作数据库,所以需要先创建模型对象。
大类Category模型对象,如下所示:
using SqlSugar;
namespace EasyBuyShop.Models
{
[SugarTable("EB_Category")]
public class Category : EntityModel
{
[SugarColumn(ColumnName ="Category")]
public string CategoryName { get; set; }
public string Description { get; set; }
}
}
小类SubCategory模型对象,如下所示:
using SqlSugar;
namespace EasyBuyShop.Models
{
[SqlSugar.SugarTable("EB_SubCategory")]
public class SubCategory : EntityModel
{
public long CategoryId { get; set; }
[SugarColumn(ColumnName = "SubCategory")]
public string SubCategoryName { get; set; }
public string Description { get; set; }
}
}
其中EntityModel为模型基类,为公共类型,如下所示:
using SqlSugar;
using System.ComponentModel.DataAnnotations.Schema;
using System.Security.Principal;
namespace EasyBuyShop.Models
{
public class EntityModel
{
[SugarColumn(IsNullable = false, IsIdentity = true)]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public DateTime CreateTime { get; set; }
public string CreateUser { get; set; }
public DateTime LastEditTime { get; set; }
public string LastEditUser { get; set; }
}
}
数据库操作类位于DAL层,每一个表都有对应的DAL层,如下所示:
大类Category数据表操作DAL层,如下所示:
using EasyBuyShop.Models;
namespace EasyBuyShop.DAL
{
public class CategoryDal:BaseDal
{
public CategoryDal()
{
}
public List GetCategories()
{
return this.getTList();
}
}
}
小类SubCategory数据表操作DAL层,如下所示:
using EasyBuyShop.Models;
namespace EasyBuyShop.DAL
{
public class SubCategoryDal : BaseDal
{
public List GetSubCategories()
{
return this.getTList();
}
}
}
其中BaseDal为基类,数据库操作的公共方法,如下所示:
using EasyBuyShop.Utils;
using SqlSugar;
namespace EasyBuyShop.DAL
{
public class BaseDal
{
public static string ConnStr = string.Empty;
///
/// 获取程序数据库操作对象
///
/// 数据库连接字符串
///
public SqlSugarClient GetDb(string strConn)
{
var db = new SqlSugarClient(
new ConnectionConfig()
{
ConnectionString = strConn,
DbType = DbType.SqlServer,
IsAutoCloseConnection = true,
InitKeyType = InitKeyType.Attribute,
AopEvents = new AopEvents
{
OnLogExecuting = (sql, p) =>
{
LogHelper.Info(sql);
LogHelper.Info(string.Join(",", p?.Select(it => it.ParameterName + ":" + it.Value)));
}
}
});
return db;
}
///
/// 查询所有的用户记录
///
///
public List getTList()
{
try
{
return this.GetDb(ConnStr).Queryable().ToList();
}
catch (Exception ex)
{
LogHelper.Fatal(ex.Message);
return null;
}
}
///
/// 插入一条记录
///
///
///
public int InsertT(T model) where T : class, new()
{
try
{
return this.GetDb(ConnStr).Insertable(model).ExecuteCommand();
}
catch (Exception ex)
{
LogHelper.Fatal(ex.Message);
return -1;
}
}
}
}
商品类型只是首页【/Home/Index】的一小部分,首页的控制器获取到商品类型信息,然后传递到视图层即可。如下所示:
public IActionResult Index()
{
CategoryDal categoryDal = new CategoryDal();
SubCategoryDal subCategoryDal = new SubCategoryDal();
var categories = categoryDal.GetCategories();
var subCategories = subCategoryDal.GetSubCategories();
ViewData["Categories"] = categories;
ViewData["SubCategories"] = subCategories;
return View();
}
商品类型视图在首页【/Home/Index.cshtml】中,如下所示:
@foreach(var category in ViewData["Categories"] as List)
{
var id = category.Id;
var subCategories = ViewData["SubCategories"] as List;
var subCategoriesById = subCategories.Where(r => r.CategoryId == id);
}
商品类型示例效果图,如下所示:
banner条主要用与广告位之类的显示,友情链接主要用于链接其他网站或者站内页面。目前banner条设计了两张静态图,友情链接参考了某宝内容,视图文件如下所示:
以上就是ASP.NET Core MVC开发实战之商城系统(一) 的全部内容,后续将继续介绍其他模块。