当前位置: 首页 > news >正文

.NET MVC 框架基础大全 - 详解

.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 项目的基础结构和核心功能。您可以根据具体需求进行扩展和定制。

http://www.hskmm.com/?act=detail&tid=27974

相关文章:

  • 实用指南:Qt QEventLoop的使用的一个问题讨论
  • 国产项目管理工具Gitee:数字化转型浪潮中的本土化破局者
  • 网络安全领域没有真正的初级岗位
  • 2025年磁翻板液位计生产商,制造商哪家好?生产厂家推荐这家!
  • Redis持久化-k8s - Soul
  • 2025年最新免费版Maxon CINEMA 4D Studio 2025下载安装教程
  • adb调试
  • 创新突破!天翼云TeleDB数据库通过中国信通院数据库迁移工具专项测试
  • Node.js基础库介绍与使用
  • gaussdb常用操作 - 吾辈当奋斗
  • Go语言熟练使用指南
  • Webpack与Vite原理深度解析
  • 2025燃气采暖锅炉实力厂家最新推荐榜:卓越品质与可靠性能口
  • 架构设计能力复习
  • 2025锅炉厂家最新推荐榜:高效节能与安全运行口碑之选
  • 前端全栈工程师技术提升建议
  • 前端技术复习与体系化框架
  • 常用pg-sql操作 - 吾辈当奋斗
  • 微信社群开发
  • IStringLocalizer突然失效?线程的“失忆症”
  • IIS8.5 安装证书
  • 软件技术基础的第一次作业
  • UMich EECS 498-007 / 598-005: Deep Learning for Computer Vision
  • n8n Docker 部署手册
  • 2025南通婚纱摄影厂家最新推荐榜:匠心工艺与浪漫美学完美结合
  • 免费音乐软件,哔哔音乐 免费下载及安装!免费音乐播放器
  • 多级缓存架构:性能与数据一致性的平衡处理(原理及优势详解+项目实战) - 教程
  • mysql设置最大连接数,MySQL最大连接数设置详解
  • 微信机器人API开放!手把手教你打造智能聊天机器人
  • 十二重计数法