ASP.NET Core 轻量化开源论坛项目,ASP.NET Core Light forum NETCoreBBS
采用 ASP.NET Core + EF Core Sqlite + Bootstrap 开发。
GitHub: https://github.com/linezero/NETCoreBBS
开发注意:默认为80端口,可能会和本地端口冲突,可以到Program.cs 中更改 .UseUrls("http://*:80"),然后更改启动URL既可。
功能 技术点大合集 架构 Clean Architecture
1. Areas
重点代码:
app.UseMvc(routes => { routes.MapRoute( name: , template: , defaults: }); routes.MapRoute( name: , template: ); });
增加一个 areaRoute ,然后添加对应的Areas 文件夹,然后Areas里的控制器里加上 [Area("Admin")] 。
2. ViewComponents在项目里的ViewComponents 文件夹,注意对应视图在 Views\Shared\Components 文件夹里。
3. MiddlewareRequestIPMiddleware 记录ip及相关信息的中间件
public class RequestIPMiddleware { private readonly RequestDelegate _next; private readonly ILogger _logger; public RequestIPMiddleware(RequestDelegate next) { _next = next; _logger = LogManager.GetCurrentClassLogger(); } public async Task Invoke(HttpContext httpContext) { var url = httpContext.Request.Path.ToString(); ) || url.Contains() || url.Contains() || url.Contains())) { _logger.Info($); } await _next(httpContext); } } RequestIPMiddlewareExtensions { public static IApplicationBuilder UseRequestIPMiddleware(this IApplicationBuilder builder) { return builder.UseMiddleware<RequestIPMiddleware>(); } }
View Code 4. Identity集成Identity ,扩展User表,自定义用户表。
权限策略
services.AddAuthorization(options => { options.AddPolicy( , authBuilder => { authBuilder.RequireClaim(, ); }); });
注册登录密码复杂度
services.AddIdentity<User, IdentityRole>(options => { options.Password = new PasswordOptions() { RequireNonAlphanumeric = false, RequireUppercase=false }; }).AddEntityFrameworkStores<DataContext>().AddDefaultTokenProviders();
5. EF Core
EF Core 采用Sqlite 数据库。
读取配置文件
services.AddDbContext<DataContext>(options => options.UseSqlite(Configuration.GetConnectionString()));
使用代码初始化数据库
private void InitializeNetCoreBBSDatabase(IServiceProvider serviceProvider) { using (var serviceScope = serviceProvider.GetRequiredService<IServiceScopeFactory>().CreateScope()) { var db = serviceScope.ServiceProvider.GetService<DataContext>(); db.Database.Migrate(); if (db.TopicNodes.Count() == 0) { db.TopicNodes.AddRange(GetTopicNodes()); db.SaveChanges(); } } }
项目分层 DataContext 在 Infrastructure,使用dotnet ef 命令注意事项
dotnet ef migrations add InitMigration --startup-project ../NetCoreBBS/NetCoreBBS.csproj更新指定字段,不用先查询实体。
public IActionResult EditSave(Topic topic) { _context.Attach(topic); _context.Entry(topic).Property(r => r.Title).IsModified = true; _context.Entry(topic).Property(r => r.Content).IsModified = true; _context.SaveChanges(); ); }
6. Configuration
读取链接字符串 Configuration.GetConnectionString("DefaultConnection")
7. Partial Views_LoginPartial.cshtml 头部登录部分分布视图
_PagerPartial.cshtml 分页分布视图
@{ var pageindex = Convert.ToInt32(ViewBag.PageIndex); var pagecount = Convert.ToInt32(ViewBag.PageCount); pagecount = pagecount == 0 ? 1 : pagecount; pageindex = pageindex > pagecount ? pagecount : pageindex; var path = Context.Request.Path.Value; var query = string.Empty; var querys = Context.Request.Query; foreach (var item in querys) { )) { query += $; } } query = query == : + query; path += query; var pagestart = pageindex - 2 > 0 ? pageindex - 2 : 1; var pageend = pagestart + 5 >= pagecount ? pagecount : pagestart + 5; } <ul > <li disabled> <a href=#{path}page={pageindex - >← 上一页</a> </li> <li @(pageindex == : href=>1</a></li> @if (pagestart > 2) { <li ><a href=>…</a></li> } @for (int i = pagestart; i < pageend; i++) { if (i > 1) { <li @(pageindex == i ? : href=>@i</a></li> } } @if (pageend < pagecount) { <li ><a href=>…</a></li> } @if (pagecount > 1) { <li @(pageindex == pagecount ? : href=>@pagecount</a></li> } <li disabled> <a rel=href=#{path}page={pageindex + >下一页 →</a> </li> </ul>
写的不是很好,可以优化成TagHelper。
8. Injecting Services Into Views@inject SignInManager<User> SignInManager
@inject 关键字
9. Dependency Injection and Controllerspublic IActionResult Index([FromServices]IUserServices user)
FromServices 在指定Action注入,也可以使用构造函数注入。