本文最后更新于 86 天前,其中的信息可能已经有所发展或是发生改变。
基本架构
model 实体
说得通俗一些,model中主要是定义前端传过来的变量以及其类型,或者是需要操作的数据库中的某些字段值。举个例子:
代码语言:javascript复制namespace Test.Models.Book
{
public class BookModel
{
public int BookId { get; set; }
public string BookName { get; set; }
public DateTime CreateDate { get; set; }
}
}
其中,上面的namespace是申明一个命名空间,Test表示解决方案,Models是实体文件夹,Book表示实体是Book。申明的每个变量都需要有它的类别以及get和set方法。
controller 控制器层
controller文件中主要定义路由的配置信息,请求方法等。举个例子:
代码语言:javascript复制using Test.BLL.Book;
using Test.Models.Book;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
namespace Test.Controllers.Book
{
[Route("api/book/[controller]/[action]")]
[ApiController]
public class Book : Controller
{
// 获取书
[HttpGet]
public async Task<ActionResult> GetBookDetail(int BookId)
{
var res = await bookBll.GetBookDetail(BookId);
return Ok(res)
}
// 添加书
[HttpPost]
public async Task<ActionResult> AddBook([FromBody] BookModel model)
{
await bookBll.AddBook(model);
return Ok("")
}
}
}
bll 业务逻辑层
bll文件中主要处理各种逻辑。
代码语言:javascript复制using Test.DAL.Book;
using Test.Models.Book;
using System.Threading.Tasks;
using System;
using System.Collections.Generic;
namespace Test.BLL.Book
{
public class Book
{
BookDal bookDal = new BookDal();
public async Task<dynamic> GetBookDetail(int BookId)
{
return await bookDal.GetBookDetail(BookId);
}
public async Task AddBook(BookModel model)
{
string BookName = model.BookName;
await bookDal.AddBook(BookName);
}
}
}
dal 数据操作层
dal文件主要用于数据库的操作。
代码语言:javascript复制using Test.BLL;
using Test.Models.Book;
using System.Threading.Tasks;
using System;
using System.Collections.Generic;
namespace Test.DAL.Book
{
public class Book
{
public async Task<dynamic> GetBookDetail(int BookId)
{
IDbConnection conn = SqlUtil.SqlConnection(ConfigUtil.GetSysSettings().Book);
string sql = @"SELECT * FROM book WHERE bookId = @bookId"
return await SqlUtil.QueryAsync<dynamic>(sql, new { bookName }, connection: conn);
}
public async Task AddBook(string BookName)
{
IDbConnection conn = SqlUtil.SqlConnection(ConfigUtil.GetSysSettings().Book);
string sql = @"INSERT INTO book(bookId,bookName,createDate) values(@bookId,@bookName,GETDATE())"
await SqlUtil.ExecuteAsync(sql, new { bookName }, connection: conn);
}
}
}
前端调用方式
src下的service文件夹的book.js
代码语言:javascript复制export async function getBookDetail(params) {
return request(`${SERVICE_BASE}/api/Book/GetBookDetail`, {
method: 'GET',
params
});
}
export async function addBook(params) {
return request(`${SERVICE_BASE}/api/Book/AddBook`, {
method: 'POST',
body: params
});
}
代码语言:javascript复制import React, { useEffect } from 'react';
import * as service from '@/services/book';
function book(){
useEffect(() => {
service.getBookDetail({bookId: 1}).then(res=>{
if (res.errorCode == 0) {
console.log(res)
}
})
service.addBook({bookName: "格列夫游记"}).then(res=>{
if (res.errorCode == 0) {
console.log(res)
}
})
})
}