昵称规则录入、审核

一、项目需求

        为了防止恶意行为,有些人可能会利用修改昵称的功能进行一些恶意的行为,比如发布不良信息、进行网络欺诈等,为了保护其他用户的权益,防止这些不良行为的发生,平台会对修改昵称的功能进行审核。

昵称审核

源码下载

二、基础实现

1、搭建SQL Server数据库环境

1)使用NetDB.sql导入数据库,包含User表和Product表。

2)NikenameRule 昵称规则表

    id  int (主键)
    context nvarchar(50)
    createDate datetime
    isDelete bit //逻辑删除

2、新建Web应用程序

        Visual Studio 2019→创建新项目→ASP.NET Web应用程序(.NET Framework)→MVC

3、DataBaseFirst模式创建EF

        右键“添加”→“新建项”→“ADO.NET实体数据模型”→“来自数据库的EF设计器”→连接数据库→勾选数据库中的两个表→勾选“确定所声称对象名称的单复数形式”

4、添加数据注解

        1)User

	[DisplayName("用户名")]
    public string username { get; set; }
    [DisplayName("昵称")]
    [Required]
    public string nikename { get; set; }

        2)NikenameRule

    [DisplayName("文本")]
    [Required]
    public string context { get; set; }

三、昵称规则分页

1、昵称规则首页
@using Webdiyer.WebControls.Mvc

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

@Html.ValidationSummary(true, "", new { @class = "text-danger" })

<div class="row" style="margin-bottom:10px">
    <div class="col-sm-4">
        <form action="/NikenameRule/BatchCreate" enctype="multipart/form-data" method="post" class="form-inline">
            <input name="file" id="file" type="file" accept=".txt" style="display: inline-block" />
            <input value="导入" type="submit" class="btn btn-primary" onclick="return beforeSubmit()" />
        </form>
    </div>
    <div class="col-sm-2">
        @Html.ActionLink("新增", "Create", new { }, new { @class = "btn btn-success" })
    </div>
</div>

<div style="margin-bottom:10px">
    @using (Ajax.BeginForm("AjaxPage", "NikenameRule", new AjaxOptions
    {
        UpdateTargetId = "ajaxDiv",
        InsertionMode = InsertionMode.Replace
    }, new { @class = "form-inline", id = "searchForm" }))
    {
        @Html.TextBox("queryStr", "", new { placeholder = "关键词", @class = "form-control", style = "width:200px" })
        @Html.Raw("&nbsp;&nbsp;")

        @Html.TextBox("submit", "搜索", new { type = "submit", @class = "btn btn-default", onclick = "return beforeSearch()" })
    }
</div>


<div id="ajaxDiv">
    @Html.Action("AjaxPage", "NikenameRule")
</div>

@section scripts
{
    @{Html.RegisterMvcPagerScriptResource();}

    <script type="text/javascript">
  function beforeSubmit() {
      if ($("#file").val().length == 0) {
          alert("请选择需要上传的txt文件");
          return false;
        }
      }
    </script>
}
2、 查询加分页

        1)AjaxPage Action

        public ActionResult AjaxPage(string queryStr = "", int pageIndex = 1, int pageSize = 10)
        {
            IQueryable<NikenameRule> nikenameRuleQueryable = dbContext.NikenameRules.Select(cr => cr);

            if (queryStr.Trim().Length > 0)
            {
                nikenameRuleQueryable = nikenameRuleQueryable.Where(cr => cr.context.Contains(queryStr.Trim()));
            }

            nikenameRuleQueryable = nikenameRuleQueryable.OrderByDescending(cr => cr.id);

            PagedList<NikenameRule> commentRulePagedList = nikenameRuleQueryable.ToPagedList(pageIndex, pageSize);

            commentRulePagedList.TotalItemCount = nikenameRuleQueryable.Count();

            return PartialView("_AjaxPage", commentRulePagedList);
        }

        2)_AjaxPage cshtml

@using Webdiyer.WebControls.Mvc
@model PagedList<NikenameProject.Models.NikenameRule>

@{Html.RenderPartial("_List", Model);}

<div class="row">
    <div class="col-sm-3 col-sm-offset-1" style="line-height: 5.428571; ">
        共 @Model.TotalPageCount 页 @Model.TotalItemCount 条记录,当前为第 @Model.CurrentPageIndex 页
    </div>
    <div class="col-sm-8">
        @Ajax.Pager(Model, new PagerOptions
        {
        PageIndexParameterName = "pageIndex",
        ContainerTagName = "ul",
        CssClass = "pagination",
        CurrentPagerItemTemplate = "<li class=\"active\"><a href=\"#\">{0}</a></li>",
        DisabledPagerItemTemplate = "<li class=\"disabled\"><a>{0}</a></li>",
        PagerItemTemplate = "<li>{0}</li>"
        }).AjaxOptions(a => a.SetUpdateTargetId("ajaxDiv").SetDataFormId("searchForm"))
    </div>
</div>

        3)_List cshtml

@using Webdiyer.WebControls.Mvc
@model PagedList<NikenameProject.Models.NikenameRule>

@{
    int index = (Model.CurrentPageIndex - 1) * Model.PageSize + 1;
}

四、录入昵称规则

1、批量录入

        BatchCreate Action

        [HttpPost]
        public ActionResult BatchCreate()
        {
            //数据库中有记录时,不支持批量导入
            int count = dbContext.NikenameRules.Count();
            if (count > 0)
            {
                ModelState.AddModelError("", "数据库中有记录时,不支持批量导入");
                return View("index");
            }

            //上传文件
            HttpPostedFileBase httpPostedFile = Request.Files["file"];
            if (httpPostedFile == null || httpPostedFile.ContentLength <= 0)
            {
                //return JavaScript("alert('文件不能为空')");
                ModelState.AddModelError("", "文件不能为空");
                return View("index");
            }
            string fileName = Guid.NewGuid() + httpPostedFile.FileName;
            string path = AppDomain.CurrentDomain.BaseDirectory + "Upload";
            try
            {
                if (!Directory.Exists(path))
                    Directory.CreateDirectory(path);
                string savePath = Path.Combine(path, fileName);
                httpPostedFile.SaveAs(savePath);

                List<NikenameRule> nikenameRules = new List<NikenameRule>();
                // 使用 StreamReader 读取文件内容
                using (StreamReader sr = new StreamReader(savePath))
                {
                    int i = 0;
                    string line;
                    while ((line = sr.ReadLine()) != null)
                    {
                        if (line.Trim().Length>0)
                        {
                            NikenameRule nikenameRule = new NikenameRule();
                            nikenameRule.context = line.Trim();                            
                            nikenameRule.createDate = DateTime.Now;
                            nikenameRule.isDelete = false;
                            nikenameRules.Add(nikenameRule);
                            i++;
                            //读取txt文本,存入list
                            if (i % 100 == 0)
                            {
                                //批量入库
                                dbContext.NikenameRules.AddRange(nikenameRules);
                                dbContext.SaveChanges();
                                nikenameRules.Clear();
                            }
                        }                        
                    }
                }
                if (nikenameRules.Count > 0)
                {
                    dbContext.NikenameRules.AddRange(nikenameRules);
                    dbContext.SaveChanges();
                }
                return RedirectToAction("index");
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", ex.Message);
                return View("index");
            }            
        }
2、单个录入

        Create Action

        [HttpPost]
        public ActionResult Create(NikenameRule nikenameRule)
        {
            if (!ModelState.IsValid) return View(nikenameRule);            

            if (dbContext.NikenameRules.Count(cr => cr.context.Equals(nikenameRule.context.Trim())) > 0)
            {
                ModelState.AddModelError("", "评论规则已存在");
                return View();
            }
            nikenameRule.createDate = DateTime.Now;
            nikenameRule.isDelete = false;

            dbContext.NikenameRules.Add(nikenameRule);
            dbContext.SaveChanges();
            return RedirectToAction("Index");
        }

五、修改昵称

1、用户列表

        List Action

   public ActionResult List()
   {
       List<User> users = dbContext.Users.Where(u => u.role == 0).ToList();
       return View(users);
   }
2、编辑用户
        public ActionResult Edit(int? id)
        {
            User user = dbContext.Users.Where(u => u.role == 0 && u.id == id).FirstOrDefault();
            return View(user);
        }
        [HttpPost]
        public ActionResult Edit(User user)
        {
            //后台数据验证
            //if (ModelState.IsValid) return View(user);

            if (user == null || String.IsNullOrEmpty(user.nikename) || user.nikename.Trim().Length == 0)
            {
                ModelState.AddModelError("", "后台数据验证失败");
                return View();
            }
            //昵称唯一性验证
            int count = dbContext.Users.Where(u => u.nikename.Equals(user.nikename.Trim())).Count();
            if (count>0)
            {
                ModelState.AddModelError("", "改昵称已被占用");
                return View();
            }

            //昵称审核
            List<string> contextList = dbContext.NikenameRules.Select(nr => nr.context).ToList();
            string regex = String.Join("|", contextList.ToArray());
            regex = regex.Replace(@"\", @"\\").Replace("{1}", ".{0,1}").Replace("{2}", ".{0,2}");
            if (Regex.IsMatch(user.nikename.Trim(),regex))
            {
                ModelState.AddModelError("", "改昵违规,请修改");
                return View();
            }

            //合规的昵称
            user.role = 0;
            user.password = "e10adc3949ba59abbe56e057f20f883e";
            user.age = 12;
            user.phone = "13355556666";
            dbContext.Users.Attach(user);
            dbContext.Entry(user).State = System.Data.Entity.EntityState.Modified;
            dbContext.SaveChanges();
            return RedirectToAction("List");
        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

勇 士 Teacher

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值