ASP.NET Core 开源论坛项目 NETCoreBBS
ASP.NET Core 輕量化開源論壇項目,ASP.NET Core Light forum NETCoreBBS
采用 ASP.NET Core + EF Core Sqlite + Bootstrap 開發。
GitHub:?https://github.com/linezero/NETCoreBBS
開發
git clone https://github.com/linezero/NETCoreBBS.git
使用 Visual Studio 2017 打開?NetCoreBBS.sln
點擊?調試->開始調試?即可運行起來,或者直接點擊工具欄上的NetCoreBBS即可。
注意:默認為80端口,可能會和本地端口沖突,可以到Program.cs 中更改?.UseUrls("http://*:80"),然后更改啟動URL既可。
功能
節點功能
主題發布
主題回復
主題篩選
用戶登錄注冊
主題置頂
后臺管理
個人中心
技術點大合集
架構?Clean Architecture
?
1. Areas
重點代碼:
app.UseMvc(routes =>{routes.MapRoute(name: "areaRoute",template: "{area:exists}/{controller}/{action}",defaults: new { action = "Index" });routes.MapRoute(name: "default",template: "{controller=Home}/{action=Index}/{id?}");});增加一個?areaRoute ,然后添加對應的Areas 文件夾,然后Areas里的控制器里加上 ?[Area("Admin")] 。
2. ViewComponents
在項目里的ViewComponents 文件夾,注意對應視圖在 Views\Shared\Components 文件夾里。
3. Middleware
RequestIPMiddleware 記錄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(); ? ? ? ?
? ?if (!(url.Contains("/css") || url.Contains("/js") || url.Contains("/images") || url.Contains("/lib"))){_logger.Info($"Url:{url} IP:{httpContext.Connection.RemoteIpAddress.ToString()} 時間:{DateTime.Now}");} ? ? ? ? ?
?await _next(httpContext);}} ?
??public static class RequestIPMiddlewareExtensions{ ? ? ?
? ? ? ?public static IApplicationBuilder UseRequestIPMiddleware(this IApplicationBuilder builder){ ? ? ?
? ?? ? ?return builder.UseMiddleware<RequestIPMiddleware>();}}
4. Identity
集成Identity ,擴展User表,自定義用戶表。
權限策略
services.AddAuthorization(options =>{options.AddPolicy( ? ? ? ? ? ? ? ? ? ?"Admin",authBuilder =>{authBuilder.RequireClaim("Admin", "Allowed");});});注冊登錄密碼復雜度
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("DefaultConnection")));使用代碼初始化數據庫
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(); ? ?? ? ? ?return RedirectToAction("Index");}
?
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){ ? ?
? ?if (!item.Key.Equals("page")){query += $"{item.Key}={item.Value}&";}}query = query == string.Empty ? "?" : "?" + query;path += query; ?
?var pagestart = pageindex - 2 > 0 ? pageindex - 2 : 1;
? ?var pageend = pagestart + 5 >= pagecount ? pagecount : pagestart + 5; }<ul class="pagination"><li class="prev previous_page @(pageindex == 1 ? "disabled" : "")"><a href="@(pageindex==1?"#":$"{path}page={pageindex - 1}")">← 上一頁</a></li><li @(pageindex == 1 ? "class=active" : "")><a rel="start" href="@(path)page=1">1</a></li>@if (pagestart > 2){ ? ? ? ?<li class="disabled"><a href="#">…</a></li>}@for (int i = pagestart; i < pageend; i++){ ? ? ? ?if (i > 1){ ? ? ? ? ? ?<li @(pageindex == i ? "class=active" : "")><a rel="next" href="@(path)page=@i">@i</a></li>}}@if (pageend < pagecount){ ? ? ?
??<li class="disabled"><a href="#">…</a></li>}@if (pagecount > 1){ ? ? ? ?<li @(pageindex == pagecount ? "class=active" : "")><a rel="end" href="@(path)page=@pagecount">@pagecount</a></li>} ? ?<li class="next next_page @(pageindex==pagecount?"disabled":"")"><a rel="next" href="@(pageindex==pagecount?"#":$"{path}page={pageindex + 1}")">下一頁 →</a></li> </ul>
寫的不是很好,可以優化成TagHelper。
8. Injecting Services Into Views
@inject SignInManager<User> SignInManager
@inject 關鍵字
9. Dependency Injection and Controllers
public IActionResult Index([FromServices]IUserServices user)
FromServices 在指定Action注入,也可以使用構造函數注入。
?? ?private IRepository<TopicNode> _node; ?
? ? ?public UserManager<User> UserManager { get; }
? ? ?public HomeController(ITopicRepository topic, IRepository<TopicNode> node, UserManager<User> userManager){_topic = topic;_node = node;UserManager = userManager;}
?
10.發布
之前寫過對應的發布文章?ASP.NET Core 發布至Linux生產環境 Ubuntu 系統
由于project.json 改成csproj,發布有所變動。
默認發布還是相同 dotnet publish,自帶運行時發布時更改csproj。
編輯 NetCoreBBS.csproj
<RuntimeIdentifiers>ubuntu.14.04-x64</RuntimeIdentifiers>后續同樣是?dotnet publish -r?ubuntu.14.04-x64
注意這個節點,默認發布的,服務器也要安裝相同版本的runtime。
<RuntimeFrameworkVersion>1.0.0</RuntimeFrameworkVersion>?
代碼里面還有一些大家可以自己去挖掘。
NETCoreBBS 在RC2 的時候就已經開始了,有很多人應該已經看過這個項目,這篇文章是讓大家更清楚的了解這個項目。
原文地址:http://www.cnblogs.com/linezero/p/NETCoreBBS.html
.NET社區新聞,深度好文,微信中搜索dotNET跨平臺或掃描二維碼關注
總結
以上是生活随笔為你收集整理的ASP.NET Core 开源论坛项目 NETCoreBBS的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Visual Studio Code:
- 下一篇: .NET Core快速入门教程 3、我的