简体中文 繁體中文 English Deutsch 한국 사람 بالعربية TÜRKÇE português คนไทย Français Japanese

站内搜索

搜索

活动公告

通知:本站资源由网友上传分享,如有违规等问题请到版务模块进行投诉,将及时处理!
10-23 09:31

掌握ASP.NET项目开发核心技能实战案例全程解析与经验分享

SunJu_FaceMall

3万

主题

166

科技点

3万

积分

大区版主

碾压王

积分
32106
发表于 2025-8-23 19:50:36 | 显示全部楼层 |阅读模式 [标记阅至此楼]

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
1. ASP.NET概述与发展历程

ASP.NET是微软推出的用于构建Web应用程序的开发框架,自2002年首次发布以来,经历了多个版本的演进。从最初的ASP.NET Web Forms,到ASP.NET MVC,再到如今的ASP.NET Core,这个框架不断适应着Web开发的变化和需求。

1.1 ASP.NET的演进

• ASP.NET Web Forms:最初的ASP.NET版本,提供了事件驱动的编程模型,类似于Windows Forms开发。
• ASP.NET MVC:引入了模型-视图-控制器架构模式,提供了更好的控制和可测试性。
• ASP.NET Web API:专门用于构建HTTP服务的框架,便于创建RESTful服务。
• ASP.NET Core:跨平台、高性能的开源框架,整合了MVC、Web API和Web Pages的功能。

1.2 ASP.NET Core的优势

ASP.NET Core作为当前最新的版本,具有以下优势:

• 跨平台支持:可在Windows、macOS和Linux上运行
• 高性能:经过优化的运行时和请求处理管道
• 模块化设计:只包含需要的功能,减少应用体积
• 开源:社区驱动的开发模式
• 统一编程模型:同时支持MVC和Web API

2. ASP.NET项目开发的核心技能

2.1 C#编程基础

C#是ASP.NET开发的主要语言,掌握C#的基础知识是必要的:
  1. // 基本语法示例
  2. public class HelloWorld
  3. {
  4.     public static void Main(string[] args)
  5.     {
  6.         Console.WriteLine("Hello, ASP.NET Core!");
  7.         
  8.         // 变量声明与使用
  9.         string message = "Welcome to ASP.NET Core development";
  10.         int version = 6;
  11.         
  12.         Console.WriteLine($"{message} - Version {version}");
  13.     }
  14. }
复制代码

2.2 依赖注入

依赖注入(DI)是ASP.NET Core的核心概念,有助于实现松耦合的代码:
  1. // 定义服务接口
  2. public interface IMessageService
  3. {
  4.     string GetMessage();
  5. }
  6. // 实现服务
  7. public class HelloWorldMessageService : IMessageService
  8. {
  9.     public string GetMessage()
  10.     {
  11.         return "Hello from DI!";
  12.     }
  13. }
  14. // 在Startup.cs中注册服务
  15. public void ConfigureServices(IServiceCollection services)
  16. {
  17.     services.AddScoped<IMessageService, HelloWorldMessageService>();
  18. }
  19. // 在控制器中使用依赖注入
  20. public class HomeController : Controller
  21. {
  22.     private readonly IMessageService _messageService;
  23.    
  24.     public HomeController(IMessageService messageService)
  25.     {
  26.         _messageService = messageService;
  27.     }
  28.    
  29.     public IActionResult Index()
  30.     {
  31.         ViewBag.Message = _messageService.GetMessage();
  32.         return View();
  33.     }
  34. }
复制代码

2.3 中间件(Middleware)

中间件是处理HTTP请求和响应的组件,它们构成一个管道:
  1. // 自定义中间件示例
  2. public class RequestTimeMiddleware
  3. {
  4.     private readonly RequestDelegate _next;
  5.    
  6.     public RequestTimeMiddleware(RequestDelegate next)
  7.     {
  8.         _next = next;
  9.     }
  10.    
  11.     public async Task Invoke(HttpContext context)
  12.     {
  13.         var startTime = DateTime.UtcNow;
  14.         
  15.         // 调用管道中的下一个中间件
  16.         await _next(context);
  17.         
  18.         var endTime = DateTime.UtcNow;
  19.         var duration = endTime - startTime;
  20.         
  21.         // 将请求处理时间添加到响应头
  22.         context.Response.Headers["X-Response-Time-Ms"] = duration.TotalMilliseconds.ToString();
  23.     }
  24. }
  25. // 在Startup.cs中配置中间件管道
  26. public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  27. {
  28.     // 使用自定义中间件
  29.     app.UseMiddleware<RequestTimeMiddleware>();
  30.    
  31.     // 其他内置中间件
  32.     app.UseStaticFiles();
  33.     app.UseRouting();
  34.     app.UseEndpoints(endpoints =>
  35.     {
  36.         endpoints.MapControllerRoute(
  37.             name: "default",
  38.             pattern: "{controller=Home}/{action=Index}/{id?}");
  39.     });
  40. }
复制代码

2.4 实体框架(EF) Core

Entity Framework Core是ASP.NET Core中的ORM框架,用于数据访问:
  1. // 定义实体模型
  2. public class Product
  3. {
  4.     public int Id { get; set; }
  5.     public string Name { get; set; }
  6.     public decimal Price { get; set; }
  7.     public string Description { get; set; }
  8.     public int CategoryId { get; set; }
  9.     public Category Category { get; set; }
  10. }
  11. public class Category
  12. {
  13.     public int Id { get; set; }
  14.     public string Name { get; set; }
  15.     public List<Product> Products { get; set; }
  16. }
  17. // 定义DbContext
  18. public class AppDbContext : DbContext
  19. {
  20.     public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
  21.     {
  22.     }
  23.    
  24.     public DbSet<Product> Products { get; set; }
  25.     public DbSet<Category> Categories { get; set; }
  26.    
  27.     protected override void OnModelCreating(ModelBuilder modelBuilder)
  28.     {
  29.         // 配置实体关系
  30.         modelBuilder.Entity<Product>()
  31.             .HasOne(p => p.Category)
  32.             .WithMany(c => c.Products)
  33.             .HasForeignKey(p => p.CategoryId);
  34.     }
  35. }
  36. // 在Startup.cs中注册DbContext
  37. public void ConfigureServices(IServiceCollection services)
  38. {
  39.     services.AddDbContext<AppDbContext>(options =>
  40.         options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
  41. }
复制代码

2.5 身份认证与授权

ASP.NET Core提供了强大的身份认证和授权系统:
  1. // 在Startup.cs中配置身份认证
  2. public void ConfigureServices(IServiceCollection services)
  3. {
  4.     services.AddDbContext<AppDbContext>(options =>
  5.         options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
  6.    
  7.     services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
  8.         .AddEntityFrameworkStores<AppDbContext>();
  9.    
  10.     services.AddRazorPages();
  11.    
  12.     // 添加基于策略的授权
  13.     services.AddAuthorization(options =>
  14.     {
  15.         options.AddPolicy("RequireAdminRole", policy =>
  16.             policy.RequireRole("Admin"));
  17.         
  18.         options.AddPolicy("AtLeast18", policy =>
  19.             policy.Requirements.Add(new MinimumAgeRequirement(18)));
  20.     });
  21. }
  22. public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  23. {
  24.     // ... 其他中间件
  25.    
  26.     app.UseAuthentication();
  27.     app.UseAuthorization();
  28.    
  29.     // ... 路由配置
  30. }
  31. // 自定义授权要求
  32. public class MinimumAgeRequirement : IAuthorizationRequirement
  33. {
  34.     public int MinimumAge { get; }
  35.    
  36.     public MinimumAgeRequirement(int minimumAge)
  37.     {
  38.         MinimumAge = minimumAge;
  39.     }
  40. }
  41. public class MinimumAgeHandler : AuthorizationHandler<MinimumAgeRequirement>
  42. {
  43.     protected override Task HandleRequirementAsync(
  44.         AuthorizationHandlerContext context,
  45.         MinimumAgeRequirement requirement)
  46.     {
  47.         var dateOfBirthClaim = context.User.FindFirst(c => c.Type == ClaimTypes.DateOfBirth);
  48.         
  49.         if (dateOfBirthClaim == null)
  50.         {
  51.             return Task.CompletedTask;
  52.         }
  53.         
  54.         var dateOfBirth = Convert.ToDateTime(dateOfBirthClaim.Value);
  55.         int calculatedAge = DateTime.Today.Year - dateOfBirth.Year;
  56.         
  57.         if (dateOfBirth > DateTime.Today.AddYears(-calculatedAge))
  58.         {
  59.             calculatedAge--;
  60.         }
  61.         
  62.         if (calculatedAge >= requirement.MinimumAge)
  63.         {
  64.             context.Succeed(requirement);
  65.         }
  66.         
  67.         return Task.CompletedTask;
  68.     }
  69. }
  70. // 在控制器或操作上应用授权
  71. [Authorize(Policy = "RequireAdminRole")]
  72. public class AdminController : Controller
  73. {
  74.     public IActionResult Index()
  75.     {
  76.         return View();
  77.     }
  78.    
  79.     [Authorize(Policy = "AtLeast18")]
  80.     public IActionResult AdultContent()
  81.     {
  82.         return View();
  83.     }
  84. }
复制代码

3. 实战案例:构建一个电子商务网站

3.1 项目规划与架构设计

在开始开发之前,我们需要规划项目的整体架构。我们将采用分层架构,包括:

• 表示层(Presentation Layer):MVC控制器和视图
• 应用服务层(Application Service Layer):业务逻辑
• 领域层(Domain Layer):核心业务模型和逻辑
• 基础设施层(Infrastructure Layer):数据访问和外部服务集成

3.2 创建项目结构

首先,我们创建一个ASP.NET Core MVC项目:
  1. dotnet new mvc -n ECommerceApp
  2. cd ECommerceApp
复制代码

然后,我们添加必要的类库项目:
  1. # 创建领域层
  2. dotnet new classlib -n ECommerceApp.Domain
  3. # 创建应用服务层
  4. dotnet new classlib -n ECommerceApp.Application
  5. # 创建基础设施层
  6. dotnet new classlib -n ECommerceApp.Infrastructure
复制代码

3.3 实现领域模型

在ECommerceApp.Domain项目中,我们定义核心业务实体:
  1. // ECommerceApp.Domain/Entities/Product.cs
  2. namespace ECommerceApp.Domain.Entities
  3. {
  4.     public class Product
  5.     {
  6.         public int Id { get; set; }
  7.         public string Name { get; set; }
  8.         public string Description { get; set; }
  9.         public decimal Price { get; set; }
  10.         public string ImageUrl { get; set; }
  11.         public int StockQuantity { get; set; }
  12.         public int CategoryId { get; set; }
  13.         public Category Category { get; set; }
  14.         public bool IsFeatured { get; set; }
  15.         public DateTime CreatedAt { get; set; }
  16.         public DateTime? UpdatedAt { get; set; }
  17.     }
  18. }
  19. // ECommerceApp.Domain/Entities/Category.cs
  20. namespace ECommerceApp.Domain.Entities
  21. {
  22.     public class Category
  23.     {
  24.         public int Id { get; set; }
  25.         public string Name { get; set; }
  26.         public string Description { get; set; }
  27.         public string ImageUrl { get; set; }
  28.         public List<Product> Products { get; set; }
  29.     }
  30. }
  31. // ECommerceApp.Domain/Entities/Customer.cs
  32. using System.Collections.Generic;
  33. namespace ECommerceApp.Domain.Entities
  34. {
  35.     public class Customer
  36.     {
  37.         public int Id { get; set; }
  38.         public string FirstName { get; set; }
  39.         public string LastName { get; set; }
  40.         public string Email { get; set; }
  41.         public string PhoneNumber { get; set; }
  42.         public List<Address> Addresses { get; set; }
  43.         public List<Order> Orders { get; set; }
  44.     }
  45. }
  46. // ECommerceApp.Domain/Entities/Order.cs
  47. using System.Collections.Generic;
  48. namespace ECommerceApp.Domain.Entities
  49. {
  50.     public class Order
  51.     {
  52.         public int Id { get; set; }
  53.         public DateTime OrderDate { get; set; }
  54.         public decimal TotalAmount { get; set; }
  55.         public string Status { get; set; }
  56.         public int CustomerId { get; set; }
  57.         public Customer Customer { get; set; }
  58.         public int ShippingAddressId { get; set; }
  59.         public Address ShippingAddress { get; set; }
  60.         public List<OrderItem> OrderItems { get; set; }
  61.     }
  62. }
  63. // ECommerceApp.Domain/Entities/OrderItem.cs
  64. namespace ECommerceApp.Domain.Entities
  65. {
  66.     public class OrderItem
  67.     {
  68.         public int Id { get; set; }
  69.         public int ProductId { get; set; }
  70.         public Product Product { get; set; }
  71.         public int Quantity { get; set; }
  72.         public decimal UnitPrice { get; set; }
  73.         public int OrderId { get; set; }
  74.         public Order Order { get; set; }
  75.     }
  76. }
  77. // ECommerceApp.Domain/Entities/Address.cs
  78. namespace ECommerceApp.Domain.Entities
  79. {
  80.     public class Address
  81.     {
  82.         public int Id { get; set; }
  83.         public string Street { get; set; }
  84.         public string City { get; set; }
  85.         public string State { get; set; }
  86.         public string PostalCode { get; set; }
  87.         public string Country { get; set; }
  88.         public int CustomerId { get; set; }
  89.         public Customer Customer { get; set; }
  90.     }
  91. }
复制代码

3.4 实现数据访问层

在ECommerceApp.Infrastructure项目中,我们实现数据访问:
  1. // ECommerceApp.Infrastructure/Data/AppDbContext.cs
  2. using ECommerceApp.Domain.Entities;
  3. using Microsoft.EntityFrameworkCore;
  4. namespace ECommerceApp.Infrastructure.Data
  5. {
  6.     public class AppDbContext : DbContext
  7.     {
  8.         public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
  9.         {
  10.         }
  11.         
  12.         public DbSet<Product> Products { get; set; }
  13.         public DbSet<Category> Categories { get; set; }
  14.         public DbSet<Customer> Customers { get; set; }
  15.         public DbSet<Order> Orders { get; set; }
  16.         public DbSet<OrderItem> OrderItems { get; set; }
  17.         public DbSet<Address> Addresses { get; set; }
  18.         
  19.         protected override void OnModelCreating(ModelBuilder modelBuilder)
  20.         {
  21.             // 配置Product实体
  22.             modelBuilder.Entity<Product>()
  23.                 .Property(p => p.Price)
  24.                 .HasColumnType("decimal(18,2)");
  25.             
  26.             modelBuilder.Entity<Product>()
  27.                 .HasOne(p => p.Category)
  28.                 .WithMany(c => c.Products)
  29.                 .HasForeignKey(p => p.CategoryId)
  30.                 .OnDelete(DeleteBehavior.Restrict);
  31.             
  32.             // 配置Order实体
  33.             modelBuilder.Entity<Order>()
  34.                 .Property(o => o.TotalAmount)
  35.                 .HasColumnType("decimal(18,2)");
  36.             
  37.             modelBuilder.Entity<Order>()
  38.                 .HasOne(o => o.Customer)
  39.                 .WithMany(c => c.Orders)
  40.                 .HasForeignKey(o => o.CustomerId)
  41.                 .OnDelete(DeleteBehavior.Restrict);
  42.             
  43.             modelBuilder.Entity<Order>()
  44.                 .HasOne(o => o.ShippingAddress)
  45.                 .WithMany()
  46.                 .HasForeignKey(o => o.ShippingAddressId)
  47.                 .OnDelete(DeleteBehavior.Restrict);
  48.             
  49.             // 配置OrderItem实体
  50.             modelBuilder.Entity<OrderItem>()
  51.                 .Property(oi => oi.UnitPrice)
  52.                 .HasColumnType("decimal(18,2)");
  53.             
  54.             modelBuilder.Entity<OrderItem>()
  55.                 .HasOne(oi => oi.Product)
  56.                 .WithMany()
  57.                 .HasForeignKey(oi => oi.ProductId)
  58.                 .OnDelete(DeleteBehavior.Restrict);
  59.             
  60.             modelBuilder.Entity<OrderItem>()
  61.                 .HasOne(oi => oi.Order)
  62.                 .WithMany(o => o.OrderItems)
  63.                 .HasForeignKey(oi => oi.OrderId)
  64.                 .OnDelete(DeleteBehavior.Cascade);
  65.             
  66.             // 配置Address实体
  67.             modelBuilder.Entity<Address>()
  68.                 .HasOne(a => a.Customer)
  69.                 .WithMany(c => c.Addresses)
  70.                 .HasForeignKey(a => a.CustomerId)
  71.                 .OnDelete(DeleteBehavior.Cascade);
  72.         }
  73.     }
  74. }
  75. // ECommerceApp.Infrastructure/Repositories/Repository.cs
  76. using ECommerceApp.Domain.Entities;
  77. using Microsoft.EntityFrameworkCore;
  78. using System;
  79. using System.Collections.Generic;
  80. using System.Linq;
  81. using System.Linq.Expressions;
  82. using System.Threading.Tasks;
  83. namespace ECommerceApp.Infrastructure.Repositories
  84. {
  85.     public class Repository<T> : IRepository<T> where T : class
  86.     {
  87.         protected readonly AppDbContext _context;
  88.         protected readonly DbSet<T> _dbSet;
  89.         
  90.         public Repository(AppDbContext context)
  91.         {
  92.             _context = context;
  93.             _dbSet = context.Set<T>();
  94.         }
  95.         
  96.         public async Task<T> GetByIdAsync(int id)
  97.         {
  98.             return await _dbSet.FindAsync(id);
  99.         }
  100.         
  101.         public async Task<IEnumerable<T>> GetAllAsync()
  102.         {
  103.             return await _dbSet.ToListAsync();
  104.         }
  105.         
  106.         public async Task<IEnumerable<T>> FindAsync(Expression<Func<T, bool>> predicate)
  107.         {
  108.             return await _dbSet.Where(predicate).ToListAsync();
  109.         }
  110.         
  111.         public async Task AddAsync(T entity)
  112.         {
  113.             await _dbSet.AddAsync(entity);
  114.         }
  115.         
  116.         public void Update(T entity)
  117.         {
  118.             _dbSet.Attach(entity);
  119.             _context.Entry(entity).State = EntityState.Modified;
  120.         }
  121.         
  122.         public void Delete(T entity)
  123.         {
  124.             if (_context.Entry(entity).State == EntityState.Detached)
  125.             {
  126.                 _dbSet.Attach(entity);
  127.             }
  128.             _dbSet.Remove(entity);
  129.         }
  130.         
  131.         public async Task SaveChangesAsync()
  132.         {
  133.             await _context.SaveChangesAsync();
  134.         }
  135.     }
  136. }
  137. // ECommerceApp.Infrastructure/Repositories/IRepository.cs
  138. using System;
  139. using System.Collections.Generic;
  140. using System.Linq.Expressions;
  141. using System.Threading.Tasks;
  142. namespace ECommerceApp.Infrastructure.Repositories
  143. {
  144.     public interface IRepository<T> where T : class
  145.     {
  146.         Task<T> GetByIdAsync(int id);
  147.         Task<IEnumerable<T>> GetAllAsync();
  148.         Task<IEnumerable<T>> FindAsync(Expression<Func<T, bool>> predicate);
  149.         Task AddAsync(T entity);
  150.         void Update(T entity);
  151.         void Delete(T entity);
  152.         Task SaveChangesAsync();
  153.     }
  154. }
  155. // ECommerceApp.Infrastructure/Repositories/ProductRepository.cs
  156. using ECommerceApp.Domain.Entities;
  157. using Microsoft.EntityFrameworkCore;
  158. using System.Collections.Generic;
  159. using System.Threading.Tasks;
  160. namespace ECommerceApp.Infrastructure.Repositories
  161. {
  162.     public class ProductRepository : Repository<Product>, IProductRepository
  163.     {
  164.         public ProductRepository(AppDbContext context) : base(context)
  165.         {
  166.         }
  167.         
  168.         public async Task<IEnumerable<Product>> GetFeaturedProductsAsync()
  169.         {
  170.             return await _dbSet
  171.                 .Include(p => p.Category)
  172.                 .Where(p => p.IsFeatured)
  173.                 .ToListAsync();
  174.         }
  175.         
  176.         public async Task<IEnumerable<Product>> GetProductsByCategoryAsync(int categoryId)
  177.         {
  178.             return await _dbSet
  179.                 .Include(p => p.Category)
  180.                 .Where(p => p.CategoryId == categoryId)
  181.                 .ToListAsync();
  182.         }
  183.         
  184.         public async Task<Product> GetProductWithDetailsAsync(int id)
  185.         {
  186.             return await _dbSet
  187.                 .Include(p => p.Category)
  188.                 .FirstOrDefaultAsync(p => p.Id == id);
  189.         }
  190.     }
  191. }
  192. // ECommerceApp.Infrastructure/Repositories/IProductRepository.cs
  193. using ECommerceApp.Domain.Entities;
  194. using System.Collections.Generic;
  195. using System.Threading.Tasks;
  196. namespace ECommerceApp.Infrastructure.Repositories
  197. {
  198.     public interface IProductRepository : IRepository<Product>
  199.     {
  200.         Task<IEnumerable<Product>> GetFeaturedProductsAsync();
  201.         Task<IEnumerable<Product>> GetProductsByCategoryAsync(int categoryId);
  202.         Task<Product> GetProductWithDetailsAsync(int id);
  203.     }
  204. }
复制代码

3.5 实现应用服务层

在ECommerceApp.Application项目中,我们实现业务逻辑:
  1. // ECommerceApp.Application/Services/ProductService.cs
  2. using ECommerceApp.Domain.Entities;
  3. using ECommerceApp.Infrastructure.Repositories;
  4. using System.Collections.Generic;
  5. using System.Threading.Tasks;
  6. namespace ECommerceApp.Application.Services
  7. {
  8.     public class ProductService : IProductService
  9.     {
  10.         private readonly IProductRepository _productRepository;
  11.         
  12.         public ProductService(IProductRepository productRepository)
  13.         {
  14.             _productRepository = productRepository;
  15.         }
  16.         
  17.         public async Task<Product> GetProductByIdAsync(int id)
  18.         {
  19.             return await _productRepository.GetProductWithDetailsAsync(id);
  20.         }
  21.         
  22.         public async Task<IEnumerable<Product>> GetAllProductsAsync()
  23.         {
  24.             return await _productRepository.GetAllAsync();
  25.         }
  26.         
  27.         public async Task<IEnumerable<Product>> GetFeaturedProductsAsync()
  28.         {
  29.             return await _productRepository.GetFeaturedProductsAsync();
  30.         }
  31.         
  32.         public async Task<IEnumerable<Product>> GetProductsByCategoryAsync(int categoryId)
  33.         {
  34.             return await _productRepository.GetProductsByCategoryAsync(categoryId);
  35.         }
  36.         
  37.         public async Task AddProductAsync(Product product)
  38.         {
  39.             product.CreatedAt = System.DateTime.Now;
  40.             await _productRepository.AddAsync(product);
  41.             await _productRepository.SaveChangesAsync();
  42.         }
  43.         
  44.         public async Task UpdateProductAsync(Product product)
  45.         {
  46.             product.UpdatedAt = System.DateTime.Now;
  47.             _productRepository.Update(product);
  48.             await _productRepository.SaveChangesAsync();
  49.         }
  50.         
  51.         public async Task DeleteProductAsync(int id)
  52.         {
  53.             var product = await _productRepository.GetByIdAsync(id);
  54.             if (product != null)
  55.             {
  56.                 _productRepository.Delete(product);
  57.                 await _productRepository.SaveChangesAsync();
  58.             }
  59.         }
  60.     }
  61. }
  62. // ECommerceApp.Application/Services/IProductService.cs
  63. using ECommerceApp.Domain.Entities;
  64. using System.Collections.Generic;
  65. using System.Threading.Tasks;
  66. namespace ECommerceApp.Application.Services
  67. {
  68.     public interface IProductService
  69.     {
  70.         Task<Product> GetProductByIdAsync(int id);
  71.         Task<IEnumerable<Product>> GetAllProductsAsync();
  72.         Task<IEnumerable<Product>> GetFeaturedProductsAsync();
  73.         Task<IEnumerable<Product>> GetProductsByCategoryAsync(int categoryId);
  74.         Task AddProductAsync(Product product);
  75.         Task UpdateProductAsync(Product product);
  76.         Task DeleteProductAsync(int id);
  77.     }
  78. }
  79. // ECommerceApp.Application/Services/OrderService.cs
  80. using ECommerceApp.Domain.Entities;
  81. using ECommerceApp.Infrastructure.Repositories;
  82. using System;
  83. using System.Collections.Generic;
  84. using System.Linq;
  85. using System.Threading.Tasks;
  86. namespace ECommerceApp.Application.Services
  87. {
  88.     public class OrderService : IOrderService
  89.     {
  90.         private readonly IRepository<Order> _orderRepository;
  91.         private readonly IRepository<OrderItem> _orderItemRepository;
  92.         private readonly IProductService _productService;
  93.         
  94.         public OrderService(
  95.             IRepository<Order> orderRepository,
  96.             IRepository<OrderItem> orderItemRepository,
  97.             IProductService productService)
  98.         {
  99.             _orderRepository = orderRepository;
  100.             _orderItemRepository = orderItemRepository;
  101.             _productService = productService;
  102.         }
  103.         
  104.         public async Task<Order> GetOrderByIdAsync(int id)
  105.         {
  106.             return await _orderRepository.GetByIdAsync(id);
  107.         }
  108.         
  109.         public async Task<IEnumerable<Order>> GetOrdersByCustomerIdAsync(int customerId)
  110.         {
  111.             return await _orderRepository.FindAsync(o => o.CustomerId == customerId);
  112.         }
  113.         
  114.         public async Task<Order> CreateOrderAsync(int customerId, int shippingAddressId, Dictionary<int, int> productQuantities)
  115.         {
  116.             var orderItems = new List<OrderItem>();
  117.             decimal totalAmount = 0;
  118.             
  119.             foreach (var item in productQuantities)
  120.             {
  121.                 var product = await _productService.GetProductByIdAsync(item.Key);
  122.                 if (product == null || product.StockQuantity < item.Value)
  123.                 {
  124.                     throw new Exception($"Product {item.Key} is not available in sufficient quantity.");
  125.                 }
  126.                
  127.                 var orderItem = new OrderItem
  128.                 {
  129.                     ProductId = item.Key,
  130.                     Quantity = item.Value,
  131.                     UnitPrice = product.Price
  132.                 };
  133.                
  134.                 orderItems.Add(orderItem);
  135.                 totalAmount += orderItem.Quantity * orderItem.UnitPrice;
  136.                
  137.                 // Update product stock
  138.                 product.StockQuantity -= item.Value;
  139.                 await _productService.UpdateProductAsync(product);
  140.             }
  141.             
  142.             var order = new Order
  143.             {
  144.                 CustomerId = customerId,
  145.                 ShippingAddressId = shippingAddressId,
  146.                 OrderDate = DateTime.Now,
  147.                 TotalAmount = totalAmount,
  148.                 Status = "Pending",
  149.                 OrderItems = orderItems
  150.             };
  151.             
  152.             await _orderRepository.AddAsync(order);
  153.             await _orderRepository.SaveChangesAsync();
  154.             
  155.             return order;
  156.         }
  157.         
  158.         public async Task UpdateOrderStatusAsync(int orderId, string status)
  159.         {
  160.             var order = await _orderRepository.GetByIdAsync(orderId);
  161.             if (order != null)
  162.             {
  163.                 order.Status = status;
  164.                 _orderRepository.Update(order);
  165.                 await _orderRepository.SaveChangesAsync();
  166.             }
  167.         }
  168.     }
  169. }
  170. // ECommerceApp.Application/Services/IOrderService.cs
  171. using ECommerceApp.Domain.Entities;
  172. using System.Collections.Generic;
  173. using System.Threading.Tasks;
  174. namespace ECommerceApp.Application.Services
  175. {
  176.     public interface IOrderService
  177.     {
  178.         Task<Order> GetOrderByIdAsync(int id);
  179.         Task<IEnumerable<Order>> GetOrdersByCustomerIdAsync(int customerId);
  180.         Task<Order> CreateOrderAsync(int customerId, int shippingAddressId, Dictionary<int, int> productQuantities);
  181.         Task UpdateOrderStatusAsync(int orderId, string status);
  182.     }
  183. }
复制代码

3.6 实现控制器和视图

在主项目中,我们实现MVC控制器和视图:
  1. // ECommerceApp/Controllers/HomeController.cs
  2. using ECommerceApp.Application.Services;
  3. using Microsoft.AspNetCore.Mvc;
  4. using System.Threading.Tasks;
  5. namespace ECommerceApp.Controllers
  6. {
  7.     public class HomeController : Controller
  8.     {
  9.         private readonly IProductService _productService;
  10.         
  11.         public HomeController(IProductService productService)
  12.         {
  13.             _productService = productService;
  14.         }
  15.         
  16.         public async Task<IActionResult> Index()
  17.         {
  18.             var featuredProducts = await _productService.GetFeaturedProductsAsync();
  19.             return View(featuredProducts);
  20.         }
  21.         
  22.         public IActionResult About()
  23.         {
  24.             return View();
  25.         }
  26.         
  27.         public IActionResult Contact()
  28.         {
  29.             return View();
  30.         }
  31.         
  32.         public IActionResult Privacy()
  33.         {
  34.             return View();
  35.         }
  36.         
  37.         [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
  38.         public IActionResult Error()
  39.         {
  40.             return View(new ErrorViewModel { RequestId = System.Diagnostics.Activity.Current?.Id ?? HttpContext.TraceIdentifier });
  41.         }
  42.     }
  43. }
  44. // ECommerceApp/Controllers/ProductsController.cs
  45. using ECommerceApp.Application.Services;
  46. using Microsoft.AspNetCore.Mvc;
  47. using System.Threading.Tasks;
  48. namespace ECommerceApp.Controllers
  49. {
  50.     public class ProductsController : Controller
  51.     {
  52.         private readonly IProductService _productService;
  53.         
  54.         public ProductsController(IProductService productService)
  55.         {
  56.             _productService = productService;
  57.         }
  58.         
  59.         // GET: Products
  60.         public async Task<IActionResult> Index()
  61.         {
  62.             var products = await _productService.GetAllProductsAsync();
  63.             return View(products);
  64.         }
  65.         
  66.         // GET: Products/Details/5
  67.         public async Task<IActionResult> Details(int id)
  68.         {
  69.             var product = await _productService.GetProductByIdAsync(id);
  70.             if (product == null)
  71.             {
  72.                 return NotFound();
  73.             }
  74.             
  75.             return View(product);
  76.         }
  77.         
  78.         // GET: Products/Create
  79.         public IActionResult Create()
  80.         {
  81.             return View();
  82.         }
  83.         
  84.         // POST: Products/Create
  85.         [HttpPost]
  86.         [ValidateAntiForgeryToken]
  87.         public async Task<IActionResult> Create([Bind("Name,Description,Price,ImageUrl,StockQuantity,CategoryId,IsFeatured")] Product product)
  88.         {
  89.             if (ModelState.IsValid)
  90.             {
  91.                 await _productService.AddProductAsync(product);
  92.                 return RedirectToAction(nameof(Index));
  93.             }
  94.             return View(product);
  95.         }
  96.         
  97.         // GET: Products/Edit/5
  98.         public async Task<IActionResult> Edit(int id)
  99.         {
  100.             var product = await _productService.GetProductByIdAsync(id);
  101.             if (product == null)
  102.             {
  103.                 return NotFound();
  104.             }
  105.             return View(product);
  106.         }
  107.         
  108.         // POST: Products/Edit/5
  109.         [HttpPost]
  110.         [ValidateAntiForgeryToken]
  111.         public async Task<IActionResult> Edit(int id, [Bind("Id,Name,Description,Price,ImageUrl,StockQuantity,CategoryId,IsFeatured,CreatedAt")] Product product)
  112.         {
  113.             if (id != product.Id)
  114.             {
  115.                 return NotFound();
  116.             }
  117.             
  118.             if (ModelState.IsValid)
  119.             {
  120.                 await _productService.UpdateProductAsync(product);
  121.                 return RedirectToAction(nameof(Index));
  122.             }
  123.             return View(product);
  124.         }
  125.         
  126.         // GET: Products/Delete/5
  127.         public async Task<IActionResult> Delete(int id)
  128.         {
  129.             var product = await _productService.GetProductByIdAsync(id);
  130.             if (product == null)
  131.             {
  132.                 return NotFound();
  133.             }
  134.             
  135.             return View(product);
  136.         }
  137.         
  138.         // POST: Products/Delete/5
  139.         [HttpPost, ActionName("Delete")]
  140.         [ValidateAntiForgeryToken]
  141.         public async Task<IActionResult> DeleteConfirmed(int id)
  142.         {
  143.             await _productService.DeleteProductAsync(id);
  144.             return RedirectToAction(nameof(Index));
  145.         }
  146.     }
  147. }
  148. // ECommerceApp/Controllers/CartController.cs
  149. using ECommerceApp.Application.Services;
  150. using Microsoft.AspNetCore.Http;
  151. using Microsoft.AspNetCore.Mvc;
  152. using System.Collections.Generic;
  153. using System.Linq;
  154. using System.Threading.Tasks;
  155. namespace ECommerceApp.Controllers
  156. {
  157.     public class CartController : Controller
  158.     {
  159.         private readonly IProductService _productService;
  160.         
  161.         public CartController(IProductService productService)
  162.         {
  163.             _productService = productService;
  164.         }
  165.         
  166.         // 获取购物车
  167.         private Dictionary<int, int> GetCart()
  168.         {
  169.             var cart = HttpContext.Session.GetObject<Dictionary<int, int>>("Cart");
  170.             if (cart == null)
  171.             {
  172.                 cart = new Dictionary<int, int>();
  173.                 HttpContext.Session.SetObject("Cart", cart);
  174.             }
  175.             return cart;
  176.         }
  177.         
  178.         // 保存购物车
  179.         private void SaveCart(Dictionary<int, int> cart)
  180.         {
  181.             HttpContext.Session.SetObject("Cart", cart);
  182.         }
  183.         
  184.         // GET: Cart
  185.         public async Task<IActionResult> Index()
  186.         {
  187.             var cart = GetCart();
  188.             var cartItems = new List<CartItemViewModel>();
  189.             
  190.             foreach (var item in cart)
  191.             {
  192.                 var product = await _productService.GetProductByIdAsync(item.Key);
  193.                 if (product != null)
  194.                 {
  195.                     cartItems.Add(new CartItemViewModel
  196.                     {
  197.                         Product = product,
  198.                         Quantity = item.Value
  199.                     });
  200.                 }
  201.             }
  202.             
  203.             return View(cartItems);
  204.         }
  205.         
  206.         // POST: Cart/Add/5
  207.         [HttpPost]
  208.         public IActionResult Add(int id, int quantity = 1)
  209.         {
  210.             var cart = GetCart();
  211.             
  212.             if (cart.ContainsKey(id))
  213.             {
  214.                 cart[id] += quantity;
  215.             }
  216.             else
  217.             {
  218.                 cart.Add(id, quantity);
  219.             }
  220.             
  221.             SaveCart(cart);
  222.             
  223.             return RedirectToAction("Index");
  224.         }
  225.         
  226.         // POST: Cart/Update/5
  227.         [HttpPost]
  228.         public IActionResult Update(int id, int quantity)
  229.         {
  230.             var cart = GetCart();
  231.             
  232.             if (cart.ContainsKey(id))
  233.             {
  234.                 if (quantity > 0)
  235.                 {
  236.                     cart[id] = quantity;
  237.                 }
  238.                 else
  239.                 {
  240.                     cart.Remove(id);
  241.                 }
  242.             }
  243.             
  244.             SaveCart(cart);
  245.             
  246.             return RedirectToAction("Index");
  247.         }
  248.         
  249.         // POST: Cart/Remove/5
  250.         [HttpPost]
  251.         public IActionResult Remove(int id)
  252.         {
  253.             var cart = GetCart();
  254.             
  255.             if (cart.ContainsKey(id))
  256.             {
  257.                 cart.Remove(id);
  258.             }
  259.             
  260.             SaveCart(cart);
  261.             
  262.             return RedirectToAction("Index");
  263.         }
  264.         
  265.         // POST: Cart/Clear
  266.         [HttpPost]
  267.         public IActionResult Clear()
  268.         {
  269.             HttpContext.Session.Remove("Cart");
  270.             return RedirectToAction("Index");
  271.         }
  272.     }
  273.    
  274.     // 购物车项视图模型
  275.     public class CartItemViewModel
  276.     {
  277.         public Product Product { get; set; }
  278.         public int Quantity { get; set; }
  279.     }
  280. }
复制代码

3.7 实现视图

以下是一些关键视图的示例:
  1. <!-- ECommerceApp/Views/Home/Index.cshtml -->
  2. @model IEnumerable<ECommerceApp.Domain.Entities.Product>
  3. @{
  4.     ViewData["Title"] = "Home";
  5. }
  6. <div class="text-center">
  7.     <h1 class="display-4">Welcome to ECommerceApp</h1>
  8.     <p>Check out our featured products below.</p>
  9. </div>
  10. <div class="row">
  11.     @foreach (var product in Model)
  12.     {
  13.         <div class="col-md-4 mb-4">
  14.             <div class="card h-100">
  15.                 <img src="@product.ImageUrl" class="card-img-top" alt="@product.Name">
  16.                 <div class="card-body">
  17.                     <h5 class="card-title">@product.Name</h5>
  18.                     <p class="card-text">@product.Description</p>
  19.                     <p class="card-text"><strong>Price: @product.Price.ToString("C")</strong></p>
  20.                     <a asp-controller="Products" asp-action="Details" asp-route-id="@product.Id" class="btn btn-primary">View Details</a>
  21.                 </div>
  22.             </div>
  23.         </div>
  24.     }
  25. </div>
复制代码
  1. <!-- ECommerceApp/Views/Products/Details.cshtml -->
  2. @model ECommerceApp.Domain.Entities.Product
  3. @{
  4.     ViewData["Title"] = "Product Details";
  5. }
  6. <div class="container">
  7.     <div class="row">
  8.         <div class="col-md-6">
  9.             <img src="@Model.ImageUrl" class="img-fluid" alt="@Model.Name">
  10.         </div>
  11.         <div class="col-md-6">
  12.             <h2>@Model.Name</h2>
  13.             <p class="text-muted">Category: @Model.Category.Name</p>
  14.             <h3 class="text-primary">@Model.Price.ToString("C")</h3>
  15.             <p>@Model.Description</p>
  16.             <p>Stock: @Model.StockQuantity units available</p>
  17.             
  18.             <form asp-controller="Cart" asp-action="Add" method="post">
  19.                 <input type="hidden" name="id" value="@Model.Id" />
  20.                 <div class="form-group">
  21.                     <label for="quantity">Quantity:</label>
  22.                     <input type="number" id="quantity" name="quantity" class="form-control" value="1" min="1" max="@Model.StockQuantity" />
  23.                 </div>
  24.                 <button type="submit" class="btn btn-primary">Add to Cart</button>
  25.             </form>
  26.         </div>
  27.     </div>
  28. </div>
复制代码
  1. <!-- ECommerceApp/Views/Cart/Index.cshtml -->
  2. @model IEnumerable<ECommerceApp.Controllers.CartItemViewModel>
  3. @{
  4.     ViewData["Title"] = "Shopping Cart";
  5. }
  6. <h2>Shopping Cart</h2>
  7. @if (!Model.Any())
  8. {
  9.     <div class="alert alert-info">
  10.         Your cart is empty.
  11.     </div>
  12. }
  13. else
  14. {
  15.     <table class="table">
  16.         <thead>
  17.             <tr>
  18.                 <th>Product</th>
  19.                 <th>Price</th>
  20.                 <th>Quantity</th>
  21.                 <th>Total</th>
  22.                 <th>Actions</th>
  23.             </tr>
  24.         </thead>
  25.         <tbody>
  26.             @foreach (var item in Model)
  27.             {
  28.                 <tr>
  29.                     <td>
  30.                         <div class="d-flex align-items-center">
  31.                             <img src="@item.Product.ImageUrl" style="width: 50px; height: 50px; object-fit: cover;" alt="@item.Product.Name" />
  32.                             <div class="ml-2">
  33.                                 <a asp-controller="Products" asp-action="Details" asp-route-id="@item.Product.Id">@item.Product.Name</a>
  34.                             </div>
  35.                         </div>
  36.                     </td>
  37.                     <td>@item.Product.Price.ToString("C")</td>
  38.                     <td>
  39.                         <form asp-action="Update" method="post" class="form-inline">
  40.                             <input type="hidden" name="id" value="@item.Product.Id" />
  41.                             <input type="number" name="quantity" value="@item.Quantity" min="1" max="@item.Product.StockQuantity" class="form-control form-control-sm" style="width: 70px;" />
  42.                             <button type="submit" class="btn btn-sm btn-outline-primary ml-1">Update</button>
  43.                         </form>
  44.                     </td>
  45.                     <td>@((item.Product.Price * item.Quantity).ToString("C"))</td>
  46.                     <td>
  47.                         <form asp-action="Remove" method="post">
  48.                             <input type="hidden" name="id" value="@item.Product.Id" />
  49.                             <button type="submit" class="btn btn-sm btn-danger">Remove</button>
  50.                         </form>
  51.                     </td>
  52.                 </tr>
  53.             }
  54.         </tbody>
  55.         <tfoot>
  56.             <tr>
  57.                 <td colspan="3" class="text-right"><strong>Total:</strong></td>
  58.                 <td><strong>@Model.Sum(i => i.Product.Price * i.Quantity).ToString("C")</strong></td>
  59.                 <td></td>
  60.             </tr>
  61.         </tfoot>
  62.     </table>
  63.    
  64.     <div class="d-flex justify-content-between">
  65.         <form asp-action="Clear" method="post">
  66.             <button type="submit" class="btn btn-outline-danger">Clear Cart</button>
  67.         </form>
  68.         
  69.         <a asp-controller="Checkout" asp-action="Index" class="btn btn-primary">Proceed to Checkout</a>
  70.     </div>
  71. }
复制代码

3.8 配置依赖注入

在Startup.cs中配置依赖注入:
  1. // ECommerceApp/Startup.cs
  2. using ECommerceApp.Application.Services;
  3. using ECommerceApp.Infrastructure.Data;
  4. using ECommerceApp.Infrastructure.Repositories;
  5. using Microsoft.AspNetCore.Builder;
  6. using Microsoft.AspNetCore.Hosting;
  7. using Microsoft.EntityFrameworkCore;
  8. using Microsoft.Extensions.Configuration;
  9. using Microsoft.Extensions.DependencyInjection;
  10. using Microsoft.Extensions.Hosting;
  11. namespace ECommerceApp
  12. {
  13.     public class Startup
  14.     {
  15.         public Startup(IConfiguration configuration)
  16.         {
  17.             Configuration = configuration;
  18.         }
  19.         public IConfiguration Configuration { get; }
  20.         // This method gets called by the runtime. Use this method to add services to the container.
  21.         public void ConfigureServices(IServiceCollection services)
  22.         {
  23.             services.AddDbContext<AppDbContext>(options =>
  24.                 options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
  25.             // 注册仓储
  26.             services.AddScoped<IProductRepository, ProductRepository>();
  27.             services.AddScoped<IRepository<Order>, Repository<Order>>();
  28.             services.AddScoped<IRepository<OrderItem>, Repository<OrderItem>>();
  29.             services.AddScoped<IRepository<Customer>, Repository<Customer>>();
  30.             services.AddScoped<IRepository<Address>, Repository<Address>>();
  31.             services.AddScoped<IRepository<Category>, Repository<Category>>();
  32.             // 注册应用服务
  33.             services.AddScoped<IProductService, ProductService>();
  34.             services.AddScoped<IOrderService, OrderService>();
  35.             services.AddControllersWithViews();
  36.             services.AddRazorPages();
  37.             // 添加Session支持
  38.             services.AddDistributedMemoryCache();
  39.             services.AddSession(options =>
  40.             {
  41.                 options.IdleTimeout = System.TimeSpan.FromMinutes(30);
  42.                 options.Cookie.HttpOnly = true;
  43.                 options.Cookie.IsEssential = true;
  44.             });
  45.         }
  46.         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  47.         public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  48.         {
  49.             if (env.IsDevelopment())
  50.             {
  51.                 app.UseDeveloperExceptionPage();
  52.             }
  53.             else
  54.             {
  55.                 app.UseExceptionHandler("/Home/Error");
  56.                 // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
  57.                 app.UseHsts();
  58.             }
  59.             app.UseHttpsRedirection();
  60.             app.UseStaticFiles();
  61.             app.UseRouting();
  62.             app.UseSession();
  63.             app.UseAuthentication();
  64.             app.UseAuthorization();
  65.             app.UseEndpoints(endpoints =>
  66.             {
  67.                 endpoints.MapControllerRoute(
  68.                     name: "default",
  69.                     pattern: "{controller=Home}/{action=Index}/{id?}");
  70.                 endpoints.MapRazorPages();
  71.             });
  72.         }
  73.     }
  74. }
复制代码

3.9 添加Session扩展方法

为了在Session中存储复杂对象,我们需要添加扩展方法:
  1. // ECommerceApp/Extensions/SessionExtensions.cs
  2. using Microsoft.AspNetCore.Http;
  3. using System.Text.Json;
  4. namespace ECommerceApp.Extensions
  5. {
  6.     public static class SessionExtensions
  7.     {
  8.         public static void SetObject<T>(this ISession session, string key, T value)
  9.         {
  10.             session.SetString(key, JsonSerializer.Serialize(value));
  11.         }
  12.         public static T GetObject<T>(this ISession session, string key)
  13.         {
  14.             var value = session.GetString(key);
  15.             return value == null ? default(T) : JsonSerializer.Deserialize<T>(value);
  16.         }
  17.     }
  18. }
复制代码

4. 开发过程中的经验分享

4.1 架构设计经验

1. 分层架构的重要性:清晰的分层架构有助于代码的维护和扩展。在我们的电子商务网站中,我们将应用分为表示层、应用服务层、领域层和基础设施层,每一层都有明确的职责。
2. 依赖注入的使用:依赖注入是实现松耦合设计的关键。通过构造函数注入,我们可以轻松地替换实现,便于单元测试和维护。
3. 仓储模式的应用:仓储模式抽象了数据访问逻辑,使业务逻辑层不直接依赖于数据访问技术。这样,我们可以轻松地切换数据存储方式,而不影响业务逻辑。

分层架构的重要性:清晰的分层架构有助于代码的维护和扩展。在我们的电子商务网站中,我们将应用分为表示层、应用服务层、领域层和基础设施层,每一层都有明确的职责。

依赖注入的使用:依赖注入是实现松耦合设计的关键。通过构造函数注入,我们可以轻松地替换实现,便于单元测试和维护。

仓储模式的应用:仓储模式抽象了数据访问逻辑,使业务逻辑层不直接依赖于数据访问技术。这样,我们可以轻松地切换数据存储方式,而不影响业务逻辑。

4.2 性能优化经验

1. 异步编程:在ASP.NET Core中,使用异步方法可以显著提高应用程序的吞吐量。特别是在I/O操作中,如数据库访问和外部API调用,异步编程可以释放线程来处理其他请求。
2. 缓存策略:对于不经常变化的数据,使用缓存可以减少数据库访问次数,提高响应速度。ASP.NET Core提供了多种缓存选项,包括内存缓存、分布式缓存和响应缓存。
3. EF Core性能优化:使用AsNoTracking()进行只读查询批量操作减少数据库往返选择性加载需要的字段使用编译查询提高重复查询的性能
4. 使用AsNoTracking()进行只读查询
5. 批量操作减少数据库往返
6. 选择性加载需要的字段
7. 使用编译查询提高重复查询的性能

异步编程:在ASP.NET Core中,使用异步方法可以显著提高应用程序的吞吐量。特别是在I/O操作中,如数据库访问和外部API调用,异步编程可以释放线程来处理其他请求。

缓存策略:对于不经常变化的数据,使用缓存可以减少数据库访问次数,提高响应速度。ASP.NET Core提供了多种缓存选项,包括内存缓存、分布式缓存和响应缓存。

EF Core性能优化:

• 使用AsNoTracking()进行只读查询
• 批量操作减少数据库往返
• 选择性加载需要的字段
• 使用编译查询提高重复查询的性能
  1. // 使用AsNoTracking()进行只读查询
  2. public async Task<IEnumerable<Product>> GetAllProductsAsync()
  3. {
  4.     return await _context.Products
  5.         .AsNoTracking()
  6.         .ToListAsync();
  7. }
  8. // 批量插入示例
  9. public async Task BulkInsertProductsAsync(IEnumerable<Product> products)
  10. {
  11.     await _context.Products.AddRangeAsync(products);
  12.     await _context.SaveChangesAsync();
  13. }
  14. // 选择性加载字段
  15. public async Task<IEnumerable<Product>> GetProductNamesAsync()
  16. {
  17.     return await _context.Products
  18.         .Select(p => new Product { Id = p.Id, Name = p.Name })
  19.         .ToListAsync();
  20. }
  21. // 编译查询示例
  22. private static readonly Func<AppDbContext, int, Task<Product>> GetProductByIdCompiled =
  23.     EF.CompileAsyncQuery((AppDbContext context, int id) =>
  24.         context.Products.FirstOrDefault(p => p.Id == id));
  25. public async Task<Product> GetProductByIdAsync(int id)
  26. {
  27.     return await GetProductByIdCompiled(_context, id);
  28. }
复制代码

4.3 安全性经验

1. 输入验证:始终验证用户输入,防止SQL注入、XSS和其他安全漏洞。ASP.NET Core提供了内置的验证特性,可以轻松地实现验证。
  1. public class Product
  2. {
  3.     public int Id { get; set; }
  4.    
  5.     [Required(ErrorMessage = "Product name is required.")]
  6.     [StringLength(100, ErrorMessage = "Product name cannot exceed 100 characters.")]
  7.     public string Name { get; set; }
  8.    
  9.     [StringLength(500, ErrorMessage = "Description cannot exceed 500 characters.")]
  10.     public string Description { get; set; }
  11.    
  12.     [Range(0.01, 10000, ErrorMessage = "Price must be between 0.01 and 10000.")]
  13.     public decimal Price { get; set; }
  14.    
  15.     [Url(ErrorMessage = "Please enter a valid URL.")]
  16.     public string ImageUrl { get; set; }
  17.    
  18.     [Range(0, int.MaxValue, ErrorMessage = "Stock quantity cannot be negative.")]
  19.     public int StockQuantity { get; set; }
  20. }
复制代码

1. 身份认证和授权:使用ASP.NET Core Identity进行用户管理,并实现基于角色的访问控制和基于策略的授权。
2. HTTPS使用:在生产环境中始终使用HTTPS,确保数据传输的安全性。
3. 敏感数据保护:使用ASP.NET Core的数据保护API来保护敏感数据,如密码、连接字符串等。

身份认证和授权:使用ASP.NET Core Identity进行用户管理,并实现基于角色的访问控制和基于策略的授权。

HTTPS使用:在生产环境中始终使用HTTPS,确保数据传输的安全性。

敏感数据保护:使用ASP.NET Core的数据保护API来保护敏感数据,如密码、连接字符串等。
  1. // 在Startup.cs中配置数据保护
  2. public void ConfigureServices(IServiceCollection services)
  3. {
  4.     services.AddDataProtection()
  5.         .PersistKeysToFileSystem(new DirectoryInfo(@"c:\keys"))
  6.         .ProtectKeysWithDpapi();
  7. }
复制代码

4.4 测试经验

1. 单元测试:为业务逻辑编写单元测试,确保代码的正确性。使用xUnit、NUnit或MSTest等测试框架,以及Moq等模拟框架。
  1. // ProductService单元测试示例
  2. using ECommerceApp.Application.Services;
  3. using ECommerceApp.Domain.Entities;
  4. using ECommerceApp.Infrastructure.Repositories;
  5. using Moq;
  6. using System.Collections.Generic;
  7. using System.Threading.Tasks;
  8. using Xunit;
  9. namespace ECommerceApp.Tests
  10. {
  11.     public class ProductServiceTests
  12.     {
  13.         [Fact]
  14.         public async Task GetProductByIdAsync_ShouldReturnProduct()
  15.         {
  16.             // Arrange
  17.             var mockRepo = new Mock<IProductRepository>();
  18.             var productId = 1;
  19.             var expectedProduct = new Product { Id = productId, Name = "Test Product" };
  20.             
  21.             mockRepo.Setup(repo => repo.GetProductWithDetailsAsync(productId))
  22.                 .ReturnsAsync(expectedProduct);
  23.             
  24.             var service = new ProductService(mockRepo.Object);
  25.             
  26.             // Act
  27.             var result = await service.GetProductByIdAsync(productId);
  28.             
  29.             // Assert
  30.             Assert.NotNull(result);
  31.             Assert.Equal(productId, result.Id);
  32.             Assert.Equal("Test Product", result.Name);
  33.         }
  34.         
  35.         [Fact]
  36.         public async Task AddProductAsync_ShouldSetCreatedAt()
  37.         {
  38.             // Arrange
  39.             var mockRepo = new Mock<IProductRepository>();
  40.             var service = new ProductService(mockRepo.Object);
  41.             var product = new Product { Name = "New Product" };
  42.             
  43.             // Act
  44.             await service.AddProductAsync(product);
  45.             
  46.             // Assert
  47.             Assert.NotEqual(default(DateTime), product.CreatedAt);
  48.             mockRepo.Verify(repo => repo.AddAsync(product), Times.Once);
  49.             mockRepo.Verify(repo => repo.SaveChangesAsync(), Times.Once);
  50.         }
  51.     }
  52. }
复制代码

1. 集成测试:使用ASP.NET Core的测试服务器进行集成测试,验证组件之间的交互。
  1. // 集成测试示例
  2. using Microsoft.AspNetCore.Mvc.Testing;
  3. using System.Net.Http;
  4. using System.Threading.Tasks;
  5. using Xunit;
  6. namespace ECommerceApp.Tests
  7. {
  8.     public class HomeControllerIntegrationTests : IClassFixture<WebApplicationFactory<Startup>>
  9.     {
  10.         private readonly WebApplicationFactory<Startup> _factory;
  11.         
  12.         public HomeControllerIntegrationTests(WebApplicationFactory<Startup> factory)
  13.         {
  14.             _factory = factory;
  15.         }
  16.         
  17.         [Fact]
  18.         public async Task IndexPage_ReturnsSuccessAndCorrectContentType()
  19.         {
  20.             // Arrange
  21.             var client = _factory.CreateClient();
  22.             
  23.             // Act
  24.             var response = await client.GetAsync("/");
  25.             
  26.             // Assert
  27.             response.EnsureSuccessStatusCode(); // Status Code 200-299
  28.             Assert.Equal("text/html; charset=utf-8",
  29.                 response.Content.Headers.ContentType.ToString());
  30.         }
  31.     }
  32. }
复制代码

1. 测试驱动开发(TDD):考虑采用TDD方法,先编写测试,然后实现功能,这样可以确保代码的可测试性和高质量。

5. 常见问题及解决方案

5.1 数据库迁移问题

问题:在开发过程中,数据库模型变更后如何更新数据库结构?

解决方案:使用Entity Framework Core的迁移功能:
  1. # 添加迁移
  2. dotnet ef migrations add AddNewPropertyToProduct
  3. # 更新数据库
  4. dotnet ef database update
复制代码

如果需要回滚到之前的迁移:
  1. # 回滚到特定迁移
  2. dotnet ef database update PreviousMigrationName
  3. # 删除最后一个迁移(如果尚未应用到数据库)
  4. dotnet ef migrations remove
复制代码

5.2 依赖注入生命周期问题

问题:如何选择正确的服务生命周期(Scoped、Singleton、Transient)?

解决方案:理解不同生命周期的含义和适用场景:

• Transient:每次请求都会创建一个新的实例。适用于轻量级、无状态服务。
• Scoped:每个作用域(如每个HTTP请求)创建一个实例。适用于EF DbContext和每个请求需要保持状态的服务。
• Singleton:整个应用程序生命周期中只创建一个实例。适用于全局配置、日志服务等。

示例:
  1. public void ConfigureServices(IServiceCollection services)
  2. {
  3.     // DbContext应该是Scoped的
  4.     services.AddDbContext<AppDbContext>(options =>
  5.         options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
  6.    
  7.     // 仓储通常也是Scoped的,与DbContext保持一致
  8.     services.AddScoped<IProductRepository, ProductRepository>();
  9.    
  10.     // 应用服务通常也是Scoped的
  11.     services.AddScoped<IProductService, ProductService>();
  12.    
  13.     // 日志服务通常是Singleton的
  14.     services.AddSingleton<ILoggerService, LoggerService>();
  15.    
  16.     // 某些工具类可能是Transient的
  17.     services.AddTransient<IEmailService, EmailService>();
  18. }
复制代码

5.3 跨域资源共享(CORS)问题

问题:当前端应用与后端API不在同一个域时,如何处理跨域请求?

解决方案:配置CORS策略:
  1. // 在Startup.cs中配置CORS
  2. public void ConfigureServices(IServiceCollection services)
  3. {
  4.     services.AddCors(options =>
  5.     {
  6.         options.AddPolicy("AllowSpecificOrigin",
  7.             builder =>
  8.             {
  9.                 builder.WithOrigins("https://example.com", "https://www.example.com")
  10.                     .AllowAnyHeader()
  11.                     .AllowAnyMethod();
  12.             });
  13.     });
  14. }
  15. public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  16. {
  17.     // ... 其他中间件
  18.    
  19.     app.UseCors("AllowSpecificOrigin");
  20.    
  21.     // ... 其他中间件
  22. }
复制代码

5.4 性能问题:N+1查询

问题:在使用EF Core时,如何避免N+1查询问题?

解决方案:使用Include和ThenInclude进行预加载:
  1. // 错误示例:会导致N+1查询问题
  2. var orders = _context.Orders.ToList();
  3. foreach (var order in orders)
  4. {
  5.     // 每个order都会触发一次数据库查询
  6.     var customer = _context.Customers.Find(order.CustomerId);
  7.     // ...
  8. }
  9. // 正确示例:使用Include预加载相关实体
  10. var orders = _context.Orders
  11.     .Include(o => o.Customer)
  12.     .Include(o => o.OrderItems)
  13.         .ThenInclude(oi => oi.Product)
  14.     .ToList();
复制代码

5.5 内存泄漏问题

问题:在ASP.NET Core应用中,如何避免内存泄漏?

解决方案:

1. 正确处理IDisposable资源:确保实现了IDisposable接口的服务被正确释放。
  1. public class MyService : IDisposable
  2. {
  3.     private readonly IDisposable _resource;
  4.    
  5.     public MyService()
  6.     {
  7.         _resource = new SomeDisposableResource();
  8.     }
  9.    
  10.     public void Dispose()
  11.     {
  12.         _resource?.Dispose();
  13.     }
  14. }
复制代码

1. 避免静态引用:静态变量会一直存在于应用程序的整个生命周期,可能导致内存泄漏。
2. 取消长时间运行的操作:使用CancellationToken来取消长时间运行的操作。

避免静态引用:静态变量会一直存在于应用程序的整个生命周期,可能导致内存泄漏。

取消长时间运行的操作:使用CancellationToken来取消长时间运行的操作。
  1. public async Task<long> ProcessDataAsync(CancellationToken cancellationToken)
  2. {
  3.     var result = 0L;
  4.    
  5.     for (int i = 0; i < int.MaxValue; i++)
  6.     {
  7.         // 检查是否已请求取消
  8.         cancellationToken.ThrowIfCancellationRequested();
  9.         
  10.         // 执行一些计算
  11.         result += i;
  12.         
  13.         // 定期检查取消请求
  14.         if (i % 1000 == 0)
  15.         {
  16.             await Task.Delay(10, cancellationToken);
  17.         }
  18.     }
  19.    
  20.     return result;
  21. }
复制代码

1. 使用内存分析工具:使用dotMemory、ANTS Memory Profiler等工具来检测内存泄漏。

6. 最佳实践和进阶建议

6.1 代码组织和结构

1. 遵循SOLID原则:单一职责原则(SRP):每个类应该只有一个改变的理由。开放封闭原则(OCP):软件实体应该对扩展开放,对修改封闭。里氏替换原则(LSP):子类型必须能够替换其基类型。接口隔离原则(ISP):客户端不应该依赖于它不使用的接口。依赖倒置原则(DIP):高层模块不应该依赖于低层模块,两者都应该依赖于抽象。
2. 单一职责原则(SRP):每个类应该只有一个改变的理由。
3. 开放封闭原则(OCP):软件实体应该对扩展开放,对修改封闭。
4. 里氏替换原则(LSP):子类型必须能够替换其基类型。
5. 接口隔离原则(ISP):客户端不应该依赖于它不使用的接口。
6. 依赖倒置原则(DIP):高层模块不应该依赖于低层模块,两者都应该依赖于抽象。
7. 使用CQRS模式:对于复杂的应用程序,考虑使用命令查询职责分离(CQRS)模式,将读取和写入操作分开。

遵循SOLID原则:

• 单一职责原则(SRP):每个类应该只有一个改变的理由。
• 开放封闭原则(OCP):软件实体应该对扩展开放,对修改封闭。
• 里氏替换原则(LSP):子类型必须能够替换其基类型。
• 接口隔离原则(ISP):客户端不应该依赖于它不使用的接口。
• 依赖倒置原则(DIP):高层模块不应该依赖于低层模块,两者都应该依赖于抽象。

使用CQRS模式:对于复杂的应用程序,考虑使用命令查询职责分离(CQRS)模式,将读取和写入操作分开。
  1. // 查询服务
  2. public interface IProductQueryService
  3. {
  4.     Task<Product> GetProductByIdAsync(int id);
  5.     Task<IEnumerable<Product>> GetAllProductsAsync();
  6.     Task<IEnumerable<Product>> GetProductsByCategoryAsync(int categoryId);
  7. }
  8. // 命令服务
  9. public interface IProductCommandService
  10. {
  11.     Task<int> CreateProductAsync(CreateProductCommand command);
  12.     Task UpdateProductAsync(UpdateProductCommand command);
  13.     Task DeleteProductAsync(int id);
  14. }
  15. // 命令示例
  16. public class CreateProductCommand
  17. {
  18.     public string Name { get; set; }
  19.     public string Description { get; set; }
  20.     public decimal Price { get; set; }
  21.     public string ImageUrl { get; set; }
  22.     public int StockQuantity { get; set; }
  23.     public int CategoryId { get; set; }
  24.     public bool IsFeatured { get; set; }
  25. }
复制代码

1. 使用领域驱动设计(DDD):对于复杂的业务领域,考虑使用DDD方法,将业务逻辑集中在领域模型中。
  1. // 领域实体示例
  2. public class Order : Entity
  3. {
  4.     private readonly List<OrderItem> _orderItems = new List<OrderItem>();
  5.    
  6.     public DateTime OrderDate { get; private set; }
  7.     public decimal TotalAmount { get; private set; }
  8.     public string Status { get; private set; }
  9.     public int CustomerId { get; private set; }
  10.     public Customer Customer { get; private set; }
  11.     public int ShippingAddressId { get; private set; }
  12.     public Address ShippingAddress { get; private set; }
  13.     public IReadOnlyCollection<OrderItem> OrderItems => _orderItems.AsReadOnly();
  14.    
  15.     // 私有构造函数,通过工厂方法创建
  16.     private Order() { }
  17.    
  18.     public static Order Create(int customerId, int shippingAddressId)
  19.     {
  20.         return new Order
  21.         {
  22.             CustomerId = customerId,
  23.             ShippingAddressId = shippingAddressId,
  24.             OrderDate = DateTime.Now,
  25.             Status = "Pending",
  26.             TotalAmount = 0
  27.         };
  28.     }
  29.    
  30.     public void AddOrderItem(Product product, int quantity)
  31.     {
  32.         if (product == null)
  33.             throw new ArgumentNullException(nameof(product));
  34.             
  35.         if (quantity <= 0)
  36.             throw new ArgumentException("Quantity must be greater than zero", nameof(quantity));
  37.             
  38.         var orderItem = new OrderItem(product, quantity);
  39.         _orderItems.Add(orderItem);
  40.         
  41.         UpdateTotalAmount();
  42.     }
  43.    
  44.     public void UpdateTotalAmount()
  45.     {
  46.         TotalAmount = _orderItems.Sum(oi => oi.TotalPrice);
  47.     }
  48.    
  49.     public void Confirm()
  50.     {
  51.         if (Status != "Pending")
  52.             throw new InvalidOperationException("Only pending orders can be confirmed");
  53.             
  54.         Status = "Confirmed";
  55.     }
  56.    
  57.     public void Ship()
  58.     {
  59.         if (Status != "Confirmed")
  60.             throw new InvalidOperationException("Only confirmed orders can be shipped");
  61.             
  62.         Status = "Shipped";
  63.     }
  64.    
  65.     public void Cancel()
  66.     {
  67.         if (Status == "Shipped" || Status == "Delivered")
  68.             throw new InvalidOperationException("Cannot cancel shipped or delivered orders");
  69.             
  70.         Status = "Cancelled";
  71.     }
  72. }
复制代码

6.2 性能优化最佳实践

1. 响应缓存:对于不经常变化的数据,使用响应缓存减少服务器负载。
  1. [ResponseCache(Duration = 60, Location = ResponseCacheLocation.Client)]
  2. public IActionResult FeaturedProducts()
  3. {
  4.     var products = _productService.GetFeaturedProducts();
  5.     return View(products);
  6. }
复制代码

1. 压缩响应:启用响应压缩减少网络传输时间。
  1. public void ConfigureServices(IServiceCollection services)
  2. {
  3.     services.AddResponseCompression(options =>
  4.     {
  5.         options.EnableForHttps = true;
  6.         options.Providers.Add<BrotliCompressionProvider>();
  7.         options.Providers.Add<GzipCompressionProvider>();
  8.     });
  9. }
  10. public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  11. {
  12.     app.UseResponseCompression();
  13.     // ...
  14. }
复制代码

1. 使用缓存标记:使用缓存标记实现缓存失效。
  1. public void ConfigureServices(IServiceCollection services)
  2. {
  3.     services.AddOutputCache(options =>
  4.     {
  5.         options.AddBasePolicy(builder => builder
  6.             .With(c => c.HttpContext.Request.Path.StartsWithSegments("/products"))
  7.             .Tag("products"));
  8.     });
  9. }
  10. // 在控制器中使用
  11. [OutputCache(Tags = new[] { "products" })]
  12. public IActionResult Details(int id)
  13. {
  14.     var product = _productService.GetProductById(id);
  15.     return View(product);
  16. }
  17. // 在更新产品时使缓存失效
  18. public IActionResult Update(Product product)
  19. {
  20.     _productService.UpdateProduct(product);
  21.     _outputCache.EvictByTagAsync("products");
  22.     return RedirectToAction(nameof(Index));
  23. }
复制代码

6.3 安全性最佳实践

1. 使用HTTPS和HSTS:确保所有通信都通过HTTPS进行,并启用HTTP严格传输安全。
  1. public void ConfigureServices(IServiceCollection services)
  2. {
  3.     services.AddHsts(options =>
  4.     {
  5.         options.Preload = true;
  6.         options.IncludeSubDomains = true;
  7.         options.MaxAge = TimeSpan.FromDays(365);
  8.     });
  9. }
  10. public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  11. {
  12.     if (env.IsDevelopment())
  13.     {
  14.         app.UseDeveloperExceptionPage();
  15.     }
  16.     else
  17.     {
  18.         app.UseExceptionHandler("/Error");
  19.         app.UseHsts();
  20.     }
  21.    
  22.     app.UseHttpsRedirection();
  23.     // ...
  24. }
复制代码

1. 实施CSRF保护:使用ASP.NET Core内置的防伪令牌功能。
  1. // 在Startup.cs中配置
  2. public void ConfigureServices(IServiceCollection services)
  3. {
  4.     services.AddAntiforgery(options =>
  5.     {
  6.         options.HeaderName = "X-XSRF-TOKEN";
  7.         options.Cookie.SameSite = SameSiteMode.Strict;
  8.         options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
  9.     });
  10. }
  11. // 在表单中包含防伪令牌
  12. <form method="post">
  13.     @Html.AntiForgeryToken()
  14.     <!-- 表单字段 -->
  15. </form>
  16. // 在AJAX请求中包含防伪令牌
  17. function getCookie(name) {
  18.     const value = `; ${document.cookie}`;
  19.     const parts = value.split(`; ${name}=`);
  20.     if (parts.length === 2) return parts.pop().split(';').shift();
  21. }
  22. fetch('/api/products', {
  23.     method: 'POST',
  24.     headers: {
  25.         'Content-Type': 'application/json',
  26.         'RequestVerificationToken': getCookie('XSRF-TOKEN')
  27.     },
  28.     body: JSON.stringify(data)
  29. });
复制代码

1. 安全配置:使用安全头增强应用程序安全性。
  1. public void ConfigureServices(IServiceCollection services)
  2. {
  3.     services.AddHsts(options =>
  4.     {
  5.         options.Preload = true;
  6.         options.IncludeSubDomains = true;
  7.         options.MaxAge = TimeSpan.FromDays(365);
  8.     });
  9. }
  10. public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  11. {
  12.     // ... 其他中间件
  13.    
  14.     app.Use(async (context, next) =>
  15.     {
  16.         context.Response.Headers.Add("X-Content-Type-Options", "nosniff");
  17.         context.Response.Headers.Add("X-Frame-Options", "DENY");
  18.         context.Response.Headers.Add("X-XSS-Protection", "1; mode=block");
  19.         context.Response.Headers.Add("Referrer-Policy", "strict-origin-when-cross-origin");
  20.         context.Response.Headers.Add("Content-Security-Policy",
  21.             "default-src 'self'; " +
  22.             "script-src 'self' 'unsafe-inline' https://cdnjs.cloudflare.com; " +
  23.             "style-src 'self' 'unsafe-inline' https://cdnjs.cloudflare.com; " +
  24.             "img-src 'self' data: https://picsum.photos; " +
  25.             "font-src 'self' https://cdnjs.cloudflare.com; " +
  26.             "connect-src 'self'; " +
  27.             "frame-ancestors 'none';");
  28.         
  29.         await next();
  30.     });
  31.    
  32.     // ... 其他中间件
  33. }
复制代码

6.4 DevOps和部署最佳实践

1. CI/CD管道:设置持续集成和持续部署管道,自动化构建、测试和部署过程。
  1. # Azure Pipelines示例
  2. trigger:
  3. - main
  4. pool:
  5.   vmImage: 'windows-latest'
  6. variables:
  7.   solution: '**/*.sln'
  8.   buildPlatform: 'Any CPU'
  9.   buildConfiguration: 'Release'
  10. steps:
  11. - task: NuGetToolInstaller@1
  12. - task: NuGetCommand@2
  13.   inputs:
  14.     restoreSolution: '$(solution)'
  15. - task: VSBuild@1
  16.   inputs:
  17.     solution: '$(solution)'
  18.     msbuildArgs: '/p:DeployOnBuild=true /p:WebPublishMethod=Package /p:PackageAsSingleFile=true /p:SkipInvalidConfigurations=true /p:PackageLocation="$(build.artifactStagingDirectory)"'
  19.     platform: '$(buildPlatform)'
  20.     configuration: '$(buildConfiguration)'
  21. - task: VSTest@2
  22.   inputs:
  23.     platform: '$(buildPlatform)'
  24.     configuration: '$(buildConfiguration)'
  25. - task: PublishBuildArtifacts@1
  26.   inputs:
  27.     pathtoPublish: '$(Build.ArtifactStagingDirectory)'
  28.     artifactName: 'drop'
复制代码

1. 容器化部署:使用Docker容器化应用程序,简化部署和环境一致性。
  1. # Dockerfile示例
  2. FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base
  3. WORKDIR /app
  4. EXPOSE 80
  5. EXPOSE 443
  6. FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
  7. WORKDIR /src
  8. COPY ["ECommerceApp/ECommerceApp.csproj", "ECommerceApp/"]
  9. COPY ["ECommerceApp.Domain/ECommerceApp.Domain.csproj", "ECommerceApp.Domain/"]
  10. COPY ["ECommerceApp.Application/ECommerceApp.Application.csproj", "ECommerceApp.Application/"]
  11. COPY ["ECommerceApp.Infrastructure/ECommerceApp.Infrastructure.csproj", "ECommerceApp.Infrastructure/"]
  12. RUN dotnet restore "ECommerceApp/ECommerceApp.csproj"
  13. COPY . .
  14. WORKDIR "/src/ECommerceApp"
  15. RUN dotnet build "ECommerceApp.csproj" -c Release -o /app/build
  16. FROM build AS publish
  17. RUN dotnet publish "ECommerceApp.csproj" -c Release -o /app/publish
  18. FROM base AS final
  19. WORKDIR /app
  20. COPY --from=publish /app/publish .
  21. ENTRYPOINT ["dotnet", "ECommerceApp.dll"]
复制代码

1. 监控和日志记录:实现全面的监控和日志记录策略,以便及时发现和解决问题。
  1. // 在Startup.cs中配置日志记录
  2. public void ConfigureServices(IServiceCollection services)
  3. {
  4.     services.AddLogging(loggingBuilder =>
  5.     {
  6.         loggingBuilder.AddConsole();
  7.         loggingBuilder.AddDebug();
  8.         loggingBuilder.AddEventSourceLogger();
  9.         
  10.         if (Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == "Production")
  11.         {
  12.             loggingBuilder.AddApplicationInsights();
  13.         }
  14.     });
  15. }
  16. // 在控制器中使用日志记录
  17. public class ProductsController : Controller
  18. {
  19.     private readonly ILogger<ProductsController> _logger;
  20.    
  21.     public ProductsController(ILogger<ProductsController> logger)
  22.     {
  23.         _logger = logger;
  24.     }
  25.    
  26.     public IActionResult Details(int id)
  27.     {
  28.         try
  29.         {
  30.             _logger.LogInformation("Getting product details for ID: {ProductId}", id);
  31.             
  32.             var product = _productService.GetProductById(id);
  33.             if (product == null)
  34.             {
  35.                 _logger.LogWarning("Product not found for ID: {ProductId}", id);
  36.                 return NotFound();
  37.             }
  38.             
  39.             return View(product);
  40.         }
  41.         catch (Exception ex)
  42.         {
  43.             _logger.LogError(ex, "Error getting product details for ID: {ProductId}", id);
  44.             return StatusCode(500, "An error occurred while processing your request.");
  45.         }
  46.     }
  47. }
复制代码

7. 总结

通过本文的实战案例和经验分享,我们深入探讨了ASP.NET项目开发的核心技能,从基础概念到高级技术,从代码实现到最佳实践。我们构建了一个完整的电子商务网站,涵盖了产品管理、购物车功能、订单处理等核心功能,并分享了在开发过程中的经验教训和解决方案。

ASP.NET Core作为一个强大、灵活的框架,为Web开发提供了丰富的功能和工具。通过掌握其核心技能,如依赖注入、中间件、Entity Framework Core、身份认证和授权等,开发者可以构建高性能、安全、可维护的Web应用程序。

在实际开发中,我们需要注重代码质量、性能优化、安全性和可维护性,遵循最佳实践,不断学习和探索新的技术和方法。希望本文的内容能够帮助读者更好地理解和掌握ASP.NET项目开发的核心技能,在实际项目中取得成功。
「七転び八起き(ななころびやおき)」
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

加入Discord频道

加入Discord频道

加入QQ社群

加入QQ社群

联系我们|小黑屋|TG频道|RSS |网站地图

Powered by Pixtech

© 2025-2026 Pixtech Team.