.NET MVC 框架基础大全
下面是一个完整的 ASP.NET Core MVC 项目基础框架指南,包含项目结构、配置、核心功能和最佳实践。
安装环境sdk,可以通过微软网站下载-dotnet-sdk-8.0.413-win-x64.exe
1. 项目创建与基本命令
# 创建新的 MVC 项目 dotnet new mvc -n YourProjectName# 进入项目目录 cd YourProjectName# 添加必要的包 dotnet add package Microsoft.EntityFrameworkCore.SqlServer dotnet add package Microsoft.EntityFrameworkCore.Tools dotnet add package Microsoft.AspNetCore.Identity.EntityFrameworkCore# 运行项目(开发模式) dotnet run --environment Development # 或简写 dotnet run dev
2. 项目结构详解
YourProjectName/ ├── Controllers/ # 控制器 ├── Models/ # 数据模型 ├── Views/ # 视图 ├── ViewModels/ # 视图模型 ├── Services/ # 业务逻辑服务 ├── Data/ # 数据访问层 ├── wwwroot/ # 静态资源 ├── Properties/ # 项目属性 │ └── launchSettings.json ├── Program.cs # 程序入口 ├── appsettings.json # 配置文件 └── YourProjectName.csproj
3. 核心配置文件
Program.cs - 现代 .NET 6+ 风格
using Microsoft.EntityFrameworkCore; using YourProjectName.Data; using YourProjectName.Services;var builder = WebApplication.CreateBuilder(args);// 添加服务到容器 builder.Services.AddControllersWithViews(); builder.Services.AddDbContext<ApplicationDbContext>(options =>options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));builder.Services.AddScoped<IUserService, UserService>(); builder.Services.AddScoped<IProductService, ProductService>();// 配置身份认证(如果需要) builder.Services.AddAuthentication(options => {options.DefaultScheme = "Cookies";options.DefaultChallengeScheme = "Google"; }) .AddCookie("Cookies") .AddGoogle("Google", options => {options.ClientId = builder.Configuration["Authentication:Google:ClientId"];options.ClientSecret = builder.Configuration["Authentication:Google:ClientSecret"]; });var app = builder.Build();// 配置 HTTP 请求管道 if (!app.Environment.IsDevelopment()) {app.UseExceptionHandler("/Home/Error");app.UseHsts(); }app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization();app.MapControllerRoute(name: "default",pattern: "{controller=Home}/{action=Index}/{id?}");// 添加自定义路由 app.MapControllerRoute(name: "admin",pattern: "admin/{controller=Dashboard}/{action=Index}/{id?}");app.Run();
appsettings.json
json
{"ConnectionStrings": {"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=YourProjectDb;Trusted_Connection=true;MultipleActiveResultSets=true"},"Logging": {"LogLevel": {"Default": "Information","Microsoft.AspNetCore": "Warning"}},"Authentication": {"Google": {"ClientId": "your_google_client_id","ClientSecret": "your_google_client_secret"}},"AllowedHosts": "*" }
4. 数据模型与数据库上下文
Models/User.cs
using System.ComponentModel.DataAnnotations;namespace YourProjectName.Models {public class User{public int Id { get; set; }[Required][StringLength(100)]public string Name { get; set; }[Required][EmailAddress]public string Email { get; set; }[DataType(DataType.Date)]public DateTime CreatedAt { get; set; } = DateTime.Now;// 导航属性public virtual ICollection<Order> Orders { get; set; }}public class Product{public int Id { get; set; }[Required][StringLength(200)]public string Name { get; set; }[DataType(DataType.Currency)]public decimal Price { get; set; }public string Description { get; set; }public bool IsActive { get; set; } = true;} }
Data/ApplicationDbContext.cs
using Microsoft.EntityFrameworkCore; using YourProjectName.Models;namespace YourProjectName.Data {public class ApplicationDbContext : DbContext{public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options){}public DbSet<User> Users { get; set; }public DbSet<Product> Products { get; set; }public DbSet<Order> Orders { get; set; }protected override void OnModelCreating(ModelBuilder modelBuilder){// 配置模型关系modelBuilder.Entity<Order>().HasOne(o => o.User).WithMany(u => u.Orders).HasForeignKey(o => o.UserId);// 数据种子modelBuilder.Entity<Product>().HasData(new Product { Id = 1, Name = "示例产品", Price = 99.99m, Description = "这是一个示例产品" });}} }
5. 服务层实现
Services/IUserService.cs
using YourProjectName.Models;namespace YourProjectName.Services {public interface IUserService{Task<List<User>> GetAllUsersAsync();Task<User> GetUserByIdAsync(int id);Task<User> CreateUserAsync(User user);Task<User> UpdateUserAsync(User user);Task<bool> DeleteUserAsync(int id);}public class UserService : IUserService{private readonly ApplicationDbContext _context;public UserService(ApplicationDbContext context){_context = context;}public async Task<List<User>> GetAllUsersAsync(){return await _context.Users.ToListAsync();}public async Task<User> GetUserByIdAsync(int id){return await _context.Users.FindAsync(id);}public async Task<User> CreateUserAsync(User user){_context.Users.Add(user);await _context.SaveChangesAsync();return user;}public async Task<User> UpdateUserAsync(User user){_context.Users.Update(user);await _context.SaveChangesAsync();return user;}public async Task<bool> DeleteUserAsync(int id){var user = await _context.Users.FindAsync(id);if (user == null) return false;_context.Users.Remove(user);await _context.SaveChangesAsync();return true;}} }
6. 控制器实现
Controllers/UsersController.cs
using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using YourProjectName.Models; using YourProjectName.Services;namespace YourProjectName.Controllers {public class UsersController : Controller{private readonly IUserService _userService;public UsersController(IUserService userService){_userService = userService;}// GET: Userspublic async Task<IActionResult> Index(){var users = await _userService.GetAllUsersAsync();return View(users);}// GET: Users/Details/5public async Task<IActionResult> Details(int? id){if (id == null){return NotFound();}var user = await _userService.GetUserByIdAsync(id.Value);if (user == null){return NotFound();}return View(user);}// GET: Users/Createpublic IActionResult Create(){return View();}// POST: Users/Create[HttpPost][ValidateAntiForgeryToken]public async Task<IActionResult> Create([Bind("Name,Email")] User user){if (ModelState.IsValid){await _userService.CreateUserAsync(user);return RedirectToAction(nameof(Index));}return View(user);}// GET: Users/Edit/5public async Task<IActionResult> Edit(int? id){if (id == null){return NotFound();}var user = await _userService.GetUserByIdAsync(id.Value);if (user == null){return NotFound();}return View(user);}// POST: Users/Edit/5[HttpPost][ValidateAntiForgeryToken]public async Task<IActionResult> Edit(int id, [Bind("Id,Name,Email,CreatedAt")] User user){if (id != user.Id){return NotFound();}if (ModelState.IsValid){try{await _userService.UpdateUserAsync(user);}catch (DbUpdateConcurrencyException){if (!await UserExists(user.Id)){return NotFound();}else{throw;}}return RedirectToAction(nameof(Index));}return View(user);}// GET: Users/Delete/5public async Task<IActionResult> Delete(int? id){if (id == null){return NotFound();}var user = await _userService.GetUserByIdAsync(id.Value);if (user == null){return NotFound();}return View(user);}// POST: Users/Delete/5[HttpPost, ActionName("Delete")][ValidateAntiForgeryToken]public async Task<IActionResult> DeleteConfirmed(int id){await _userService.DeleteUserAsync(id);return RedirectToAction(nameof(Index));}private async Task<bool> UserExists(int id){return await _userService.GetUserByIdAsync(id) != null;}} }
7. 视图实现
Views/Users/Index.cshtml
@model IEnumerable<YourProjectName.Models.User>@{ViewData["Title"] = "用户列表"; }<h1>用户列表</h1><p><a asp-action="Create" class="btn btn-primary">创建新用户</a> </p><table class="table table-striped"><thead><tr><th>@Html.DisplayNameFor(model => model.Name)</th><th>@Html.DisplayNameFor(model => model.Email)</th><th>@Html.DisplayNameFor(model => model.CreatedAt)</th><th>操作</th></tr></thead><tbody> @foreach (var item in Model) {<tr><td>@Html.DisplayFor(modelItem => item.Name)</td><td>@Html.DisplayFor(modelItem => item.Email)</td><td>@Html.DisplayFor(modelItem => item.CreatedAt)</td><td><a asp-action="Edit" asp-route-id="@item.Id" class="btn btn-sm btn-warning">编辑</a><a asp-action="Details" asp-route-id="@item.Id" class="btn btn-sm btn-info">详情</a><a asp-action="Delete" asp-route-id="@item.Id" class="btn btn-sm btn-danger">删除</a></td></tr> }</tbody> </table>
8. 视图模型
ViewModels/UserViewModel.cs
using System.ComponentModel.DataAnnotations;namespace YourProjectName.ViewModels {public class UserViewModel{public int Id { get; set; }[Required(ErrorMessage = "姓名是必填项")][Display(Name = "姓名")][StringLength(100, ErrorMessage = "姓名长度不能超过100个字符")]public string Name { get; set; }[Required(ErrorMessage = "邮箱是必填项")][EmailAddress(ErrorMessage = "请输入有效的邮箱地址")][Display(Name = "邮箱地址")]public string Email { get; set; }[DataType(DataType.Password)][Display(Name = "密码")]public string Password { get; set; }[DataType(DataType.Password)][Display(Name = "确认密码")][Compare("Password", ErrorMessage = "密码和确认密码不匹配")]public string ConfirmPassword { get; set; }} }
9. 中间件和过滤器
Filters/LogActionFilter.cs
using Microsoft.AspNetCore.Mvc.Filters;namespace YourProjectName.Filters {public class LogActionFilter : IActionFilter{private readonly ILogger<LogActionFilter> _logger;public LogActionFilter(ILogger<LogActionFilter> logger){_logger = logger;}public void OnActionExecuting(ActionExecutingContext context){_logger.LogInformation($"执行动作: {context.ActionDescriptor.DisplayName}");}public void OnActionExecuted(ActionExecutedContext context){_logger.LogInformation($"动作执行完成: {context.ActionDescriptor.DisplayName}");}} }
10. 项目文件配置
YourProjectName.csproj
xml
<Project Sdk="Microsoft.NET.Sdk.Web"><PropertyGroup><TargetFramework>net8.0</TargetFramework><Nullable>enable</Nullable><ImplicitUsings>enable</ImplicitUsings></PropertyGroup><ItemGroup><PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="8.0.0" /><PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="8.0.0" /><PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="8.0.0" /><PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.0" /></ItemGroup></Project>
11. 数据库迁移命令
# 创建迁移 dotnet ef migrations add InitialCreate# 更新数据库 dotnet ef database update# 删除迁移 dotnet ef migrations remove# 生成数据库脚本 dotnet ef migrations script
12. 开发和生产环境配置
appsettings.Development.json
json
{"ConnectionStrings": {"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=YourProjectDb_Dev;Trusted_Connection=true;MultipleActiveResultSets=true"},"Logging": {"LogLevel": {"Default": "Information","Microsoft.AspNetCore": "Information"}} }
appsettings.Production.json
{"ConnectionStrings": {"DefaultConnection": "Server=production-server;Database=YourProjectDb;User Id=username;Password=password;"},"Logging": {"LogLevel": {"Default": "Warning","Microsoft.AspNetCore": "Warning"}} }
这个框架大全涵盖了 ASP.NET Core MVC 项目的基础结构和核心功能。您可以根据具体需求进行扩展和定制。