ASP.NET Core 轻量化开源论坛项目,ASP.NET Core Light forum NETCoreBBS

采用 ASP.NET Core + EF Core Sqlite + Bootstrap 开发。

GitHub: https://github.com/linezero/NETCoreBBS

开发

  1. git clone https://github.com/linezero/NETCoreBBS.git

  2. 使用 Visual Studio 2017 打开 NetCoreBBS.sln

  3. 点击 调试->开始调试 即可运行起来,或者直接点击工具栏上的NetCoreBBS即可。

注意:默认为80端口,可能会和本地端口冲突,可以到Program.cs 中更改 .UseUrls("http://*:80"),然后更改启动URL既可。

功能

  1. 节点功能

  2. 主题发布

  3. 主题回复

  4. 主题筛选

  5. 用户登录注册

  6. 主题置顶

  7. 后台管理

  8. 个人中心

技术点大合集

架构 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}")">&#8592; 上一页</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="#">&hellip;</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="#">&hellip;</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}")">下一页 &#8594;</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 ITopicRepository _topic;       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相关推荐

  1. core webapi缩略图_在ASP.NET Core Web API 项目里无法访问(wwwroot)下的文件

    新建 ASP.NET Core Web API 项目 -- RESTFul 风格 Hello World! 一.创建一个空项目 请查看 新建 .NET Core 项目 -- Hello World!  ...

  2. ASP.NET Core 开源项目 nopCommerce,一款沉淀13年的电商开源佳作!

    技术在不断更新迭代,.NET 6 的正式版也即将正式发布,在.NET Core 开源项目方面,CMS的代表作是SiteServer,商城的开源系统有没有什么代表作? 肯定是有的,强烈推荐这套开源免费的 ...

  3. ASP.NET Core 介绍和项目解读

    1. 前言 2. ASP.NET Core 简介 2.1 什么是ASP.NET Core 2.2 ASP.NET Core的特点 2.3 ASP.NET Core 项目文件夹解读 2.3.1 项目文件 ...

  4. 推荐:适合小白入门的Asp.Net Core 开源学习手册

    前言 推荐一个入门级的.NET Core开源项目,非常适合新手入门学习.NET Core. 开源地址: https://github.com/windsting/little-aspnetcore-b ...

  5. Asp.NET Core 轻松学-项目目录和文件作用介绍

    前言     上一章介绍了 Asp.Net Core 的前世今生,并创建了一个控制台项目编译并运行成功,本章的内容介绍 .NETCore 的各种常用命令.Asp.Net Core MVC 项目文件目录 ...

  6. ASP.NET Core 2.2 项目升级至 3.0 备忘录

    .NET Core 3.0及ASP.NET Core 3.0 前瞻 ASP.NET Core 3.0 迁移避坑指南 将 ASP.NET Core 2.2 迁移至 ASP.NET Core 3.0 需要 ...

  7. [译]使用LazZiya.ExpressLocalization开发多语言支持的ASP.NET Core 2.x项目

    介绍 开发多语言支持的ASP.NET Core 2.x Web应用程序需要大量的基础架构设置,并且耗费时间和精力.这篇文章,我们将使用LazZiya.ExpressLocalization nuget ...

  8. ASP.NET Core开源Web应用程序框架ABP

    "作为面向服务架构(SOA)的一个变体,微服务是一种将应用程序分解成松散耦合服务的新型架构风格. 通过细粒度的服务和轻量级的协议,微服务提供了更多的模块化,使应用程序更容易理解,开发,测试, ...

  9. ASP.NET Core 3.0 项目开始“瘦身”

    新的 ASP.NET Core 项目使用名为Microsoft.AspNetCore.App的综合包.该包也可以称为"ASP.NET Core 共享框架",其背后的基本思想是,包括 ...

最新文章

  1. Leangoo看板工具做单团队敏捷开发
  2. Git 基本工作流程
  3. Python 学习笔记(2)创建文件夹
  4. 我是状态机,有一颗永远骚动的机器引擎
  5. 专接本汇编开发工具【Masm for Winodws 集成实验环境】安装细则
  6. python super()(转载)
  7. BeetleX之TCP消息通讯Protobuf/TLS
  8. 白中英 计算机组成原理_白中英《计算机组成原理》(第5版)笔记和课后习题答案详解...
  9. javaweb(09) EL表达式JSTL标签库(jsp相关,了解)
  10. (Sublime Text 3)完美替换 GAMS 难用的编辑器
  11. 马云:我不懂技术,但我尊重技术(附演讲全文
  12. 20210211 plecs diode rectifier 二极管整流电路 zero crossing 报错
  13. ora01950-对象空间无权限
  14. Mac Android Studio Flutter环境配置之第一个Futter项目
  15. SuperMap 基本概念
  16. Python的Code对象
  17. 在线机器学习Topic推荐-AMiner
  18. “寻找下一代CTO”-- 机会啊
  19. 技术人生:真的要注意身体了,坚持锻炼
  20. could not create folder “sftp://xxx.xxx.xxx.xxx/.../venv“. (Permission denied)

热门文章

  1. Scala-2.13.0 安装及配置
  2. leetcode 104. Maximum Depth of Binary Tree
  3. 对抗告警疲劳的8种方法
  4. UML实践----用例图、顺序图、状态图、类图、包图、协作图
  5. iNeuOS工业互联网操作系统,顺利从NetCore3.1升级到Net6的过程汇报,发布3.7版本...
  6. 想说爱你不容易 | 使用最小 WEB API 实现文件上传(Swagger 支持)
  7. 真快!10秒内将k8s集群运行起来
  8. 如何使用 C# 判断一个文件是否为程序集
  9. Windows 11 操作系统最低硬件要求
  10. 毕业二十年,为什么人和人之间的差距那么大?