.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(options =>options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
builder.Services.AddScoped();
builder.Services.AddScoped();
// 配置身份认证(如果需要)
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 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 options): base(options){}public DbSet Users { get; set; }public DbSet Products { get; set; }public DbSet Orders { get; set; }protected override void OnModelCreating(ModelBuilder modelBuilder){// 配置模型关系modelBuilder.Entity().HasOne(o => o.User).WithMany(u => u.Orders).HasForeignKey(o => o.UserId);// 数据种子modelBuilder.Entity().HasData(new Product { Id = 1, Name = "示例产品", Price = 99.99m, Description = "这是一个示例产品" });}}
}
5. 服务层实现
Services/IUserService.cs
using YourProjectName.Models;
namespace YourProjectName.Services
{public interface IUserService{Task> GetAllUsersAsync();Task GetUserByIdAsync(int id);Task CreateUserAsync(User user);Task UpdateUserAsync(User user);Task DeleteUserAsync(int id);}public class UserService : IUserService{private readonly ApplicationDbContext _context;public UserService(ApplicationDbContext context){_context = context;}public async Task> GetAllUsersAsync(){return await _context.Users.ToListAsync();}public async Task GetUserByIdAsync(int id){return await _context.Users.FindAsync(id);}public async Task CreateUserAsync(User user){_context.Users.Add(user);await _context.SaveChangesAsync();return user;}public async Task UpdateUserAsync(User user){_context.Users.Update(user);await _context.SaveChangesAsync();return user;}public async Task 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 Index(){var users = await _userService.GetAllUsersAsync();return View(users);}// GET: Users/Details/5public async Task 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 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 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 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 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 DeleteConfirmed(int id){await _userService.DeleteUserAsync(id);return RedirectToAction(nameof(Index));}private async Task UserExists(int id){return await _userService.GetUserByIdAsync(id) != null;}}
}
7. 视图实现
Views/Users/Index.cshtml
@model IEnumerable
@{ViewData["Title"] = "用户列表";
}
用户列表创建新用户@Html.DisplayNameFor(model => model.Name)@Html.DisplayNameFor(model => model.Email)@Html.DisplayNameFor(model => model.CreatedAt)操作
@foreach (var item in Model) {@Html.DisplayFor(modelItem => item.Name)@Html.DisplayFor(modelItem => item.Email)@Html.DisplayFor(modelItem => item.CreatedAt)编辑详情删除
}
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 _logger;public LogActionFilter(ILogger 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
net8.0enableenable
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 项目的基础结构和核心功能。您可以根据具体需求进行扩展和定制。