在B/S系統開發中,前后端分離開發設計已成為一種標準,而VUE作為前端三大主流框架之一,越來越受到大家的青睞,Antdv是Antd在Vue中的實現。本系列文章主要通過Antdv和Asp.net WebApi開發學生信息管理系統,簡述前后端分離開發的主要相關內容,僅供學習分享使用,如有不足之處,還請指正。
在本示例項目中,主要包含兩大部分:1.前端web項目【vsims.web】2.后端webapi項目【vsims.webapi】,經過前一篇文章的講解,已經對前端項目的架構和組成部分有了大致了解,今天繼續后端webapi項目的開發講解及前后端接口調用示例。
在本示例中,涉及知識點包含前端和后端兩部分:
前端項目涉及知識點如下:
開發工具:HbuilderX
項目框架:VUE3.0+Antdv
后端項目涉及知識點如下:
開發工具:Visual Studio 2022
項目類型:Asp.net WebApi
數據庫:SQL Server 2012
在學生信息管理系統中,學生,班級,課程,成績等內容和管理模塊的相關內容,都離不開數據庫的支持,所以數據是支撐,頁面是對數據的展示。根據系統功能設計,對應數據庫如下所示:
關于具體表結構說明,之前已有說明,本文不再贅述,可參考文章:WPF開發學生信息管理系統【WPF+Prism+MAH+WebApi】(二)
在VS2022中文件--新建,打開創建新項目窗口,然后選擇【ASP.NET Core Web API】項目類型,點擊下一步,如下所示:
在配置新項目頁面,輸入項目名稱,和保存位置,點擊下一步,如下所示:
選擇項目對應框架,默認.NET 6.0
項目創建成功后,添加數據庫表對應的實體類,如下圖所示:
本示例中所需要的第三方框架主要有三個,如下所示:
EntityFramework框架主要用于操作數據庫,是微軟提供的通過ORM方式操作數據的框架。
Autofac框架,主要用于類的依賴注入的自動實現。
Swagger框架,主要用于WebApi在瀏覽器端的可視化展示。
第三方框架主要通過Nuget包進行安裝,如下所示:
在Asp.net WebApi項目中,采用三層架構的方式進行開發接口,如下所示:
關于具體實現類的代碼,之前已有說明,本文不再贅述,可參考文章:WPF開發學生信息管理系統【WPF+Prism+MAH+WebApi】(二)
在上述接口開發完成后,需要配置注入DataCotext和Autofac等內容,如下所示:
using Autofac;
using Autofac.Extensions.DependencyInjection;
using Microsoft.EntityFrameworkCore;
using VSIMS.WebApi;
using VSIMS.WebApi.Data;
using VSIMS.WebApi.Services.Student;
using System.Configuration;
using System.Reflection;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddDbContext<DataContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("Default")));
// 以下是autofac依賴注入
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
builder.Host.ConfigureContainer<ContainerBuilder>(builder =>
{ // 注入Service程序集
string assemblyName = Assembly.GetExecutingAssembly().GetName().Name;
builder.RegisterAssemblyTypes(Assembly.Load(assemblyName))
.AsImplementedInterfaces()
.InstancePerDependency();
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
在VS中運行程序,如果顯示接口列表,則表示成功。如下所示:
在VUE3.0的前端項目中,如果需要調用WebApi,需要先安裝第三方插件Axios以及vue-axios,安裝命令為:
npm -i --save axios
npm -i --save vue-axios
安裝過程,如下圖所示:
在src目錄下創建api目錄,并創建config.js,配置接口訪問基本地址,如下所示:
export default {
baseUrl: {
dev: "http://localhost:5151/", // 開發環境
// fat: 'http://xxx.xx.xx.xx:8080'
//uat : "http://production.com"
//pro:"http://localhost:8088/"
},
};
然后在api目錄下,創建http.js文件,封裝axios訪問,如下所示:
import axios from "axios"; // 引用axios
import config from "@/api/config";
const instance = axios.create({
baseURL: config.baseUrl.dev,
timeout: 60000,
});
//get請求
export function get(url, params = {}) {
return new Promise((resolve, reject) => {
instance
.get(url, {
params: params,
})
.then((response) => {
resolve(response);
})
.catch((err) => {
reject(err);
});
});
}
//post請求
export function post(url, data = {}) {
return new Promise((resolve, reject) => {
instance.post(url, data).then(
(response) => {
resolve(response.data);
},
(err) => {
reject(err);
}
);
});
}
然后創建index.js,封裝get和post方法,如下所示:
// index.js 調用接口的方法
// 引入封裝的get/post請求方法
import {
get,
post
} from '@/api/http'
export const getD = (url, m) => get(url, m)
export const postD = (url, m) => post(url, m)
封裝完成后,在LoginView登錄視圖中,調用接口,如下所示:
引入index.js封裝的方法,如下所示:
import { getD } from '../api/index.js';
在登錄事件中,調用接口,輸出接口返回信息,如下所示:
const onFinish = (values: any) => {
console.log(values);
console.log('Success:', values);
getD('/api/Login/Login',{"username":values.username,"password":values.password}).then(res=> {
console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>");
console.log(res);
console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>");
router.push('/home');
})
.catch(error=>{
console.log(error)
});
//this.$router.push('/home');
};
然后運行程序,輸入用戶名密碼,點擊登錄按鈕,然后提示如下錯誤:
以上錯誤是前端項目和后端WebApi是兩個獨立的項目,不屬于同一個域,所以會報跨域問題。在Vue3.0中,要解決跨域問題,需要在vue.config.js中增加跨域配置。如下所示:
const {
defineConfig
} = require('@vue/cli-service');
const webpack = require('webpack');
module.exports = defineConfig({
css: {
loaderOptions: {
less: {
lessOptions: {
modifyVars: {
'primary-color': '#1DA57A',
'link-color': '#1DA57A',
'border-radius-base': '2px',
},
javascriptEnabled: true,
},
},
},
},
chainWebpack: config => {
config
.plugin('html')
.tap(args => {
args[0].title = 'SIMS'
return args
})
},
transpileDependencies: true,
configureWebpack: {
devServer: {
host:'localhost',
port:8080,
proxy: {
'/api': { // /api是習慣性的寫法,可以隨意改
target: 'http://localhost:5151/', //接口域名
changeOrigin: true, //是否跨域
}
}
}
}
})
通過登錄接口窗口返回的狀態碼以及返回值,判斷是否登錄成功,如果成功,則跳轉到主頁面,如果失敗,則提示錯誤信息,如下所示:
const onFinish = (values: any) => {
console.log(values);
console.log('Success:', values);
getD('/Login/Login',{"username":values.username,"password":values.password}).then(res=> {
if(res.status==200){
//返回成功
if(res.data>0){
sessionStorage['UserId']=values.username;
sessionStorage['LoginId']=res.data;
message.success('登錄成功!');
router.push('/home');
}else{
message.error('登錄失敗,用戶命名錯誤!');
}
}else if(res.status==204){
//沒有返回
message.error('用戶命名錯誤!');
}else{
message.error('系統錯誤!');
}
})
.catch(error=>{
console.log(error)
});
//this.$router.push('/home');
};
啟動項目后,在瀏覽器中輸入網址,操作如下所示:
以上就是Antdv+Asp.net WebApi開發學生信息管理系統第二篇的全部內容,寫文不易,多謝支持。學習編程,從關注【老碼識途】開始!!!