一、启动Visual Studio 2019,创建ASP.NET Core Web应用程序
二、在Models文件夹添加新项 Person.cs
using System.ComponentModel.DataAnnotations; using Microsoft.AspNetCore.Mvc; namespace 信息采集系统.Models { public class Person { [Display(Name = "编号")] public int ID { get; set; } [Display(Name = "姓名")] [Required(ErrorMessage = "必须输入姓名")] [Remote("CheckName", "MyValidation")] public string Name { get; set; } [Display(Name = "性别")] public Gender Gender { get; set; } [Display(Name = "手机号")] [Required(ErrorMessage = "必须输入手机号码")] [StringLength(11, ErrorMessage = "手机号码长度应为11位", MinimumLength = 11)] public string Mobile { get; set; } [Remote("CheckFatherName", "MyValidation")] public string FatherName { get; set; } [Remote("CheckMotherName", "MyValidation")] public string MotherName { get; set; } [Display(Name = "邀请码")] [Required(ErrorMessage = "必须输入认证码")] [Remote("CheckInvitationCode", "MyValidation")] public string InvitationCode { get; set; } } public enum Gender { [Display(Name = "男")] Male = 1, [Display(Name = "女")] Female = 2 } }
三、在Controllers文件夹,添加“新搭建基架的项目”
点击数据上下文右侧的加号按钮,新建一个数据上下文类
修改StartUp.cs
public void ConfigureServices(IServiceCollection services) { services.Configure<CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); services.AddDbContext<PersonContext>(options => options.UseSqlServer(PersonContext.ConnectionString)); }
修改PersonContext.cs
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; namespace 信息采集系统.Models { public class PersonContext : DbContext { public static string ConnectionString { get { var path = AppDomain.CurrentDomain.BaseDirectory; var DatabasePath = System.IO.Path.Combine(new string[] { path, "Person.mdf" }); var s = $"Data Source=(LocalDB)\\MSSQLLocalDB;Initial Catalog=Person;AttachDbFilename={DatabasePath};"; return s; } } public PersonContext (DbContextOptions<PersonContext> options) : base(options) { } public DbSet<信息采集系统.Models.Person> Person { get; set; } } }
四、添加控制器MyValidationController.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; namespace 信息采集系统.Controllers { public class MyValidationController : Controller { private Models.PersonContext _context { get; set; } public MyValidationController(Models.PersonContext context) { this._context = context; } public JsonResult CheckName(string Name) { var chinese= Common.PinyinHelper.IsChineseString(Name); if (chinese) { return Json(true); } else { return Json("姓名必须输入中文"); } } public JsonResult CheckFatherName(string FatherName) { var chinese = Common.PinyinHelper.IsChineseString(FatherName); if (chinese) { return Json(true); } else { return Json("姓名必须输入中文"); } } public JsonResult CheckMotherName(string MotherName) { var chinese = Common.PinyinHelper.IsChineseString(MotherName); if (chinese) { return Json(true); } else { return Json("姓名必须输入中文"); } } public JsonResult CheckInvitationCode(string InvitationCode) { var b = Common.InvitationCode.IsValid(InvitationCode); if (b) { var item = _context.Person.FirstOrDefault(x => x.InvitationCode == InvitationCode); if (item == null) { return Json(true); } else { return Json($"此邀请码已被使用,使用人:{item.Name}"); } } else { return Json("错误的邀请码"); } } } }
五、添加控制器Database.cs,用于创建数据库和删除数据库。
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; namespace 信息采集系统.Controllers { public class DatabaseController : Controller { private Models.PersonContext _context { get; set; } public DatabaseController(Models.PersonContext context) { this._context = context; } public string Create() { var isCreated = _context.Database.EnsureCreated(); return $"Create={isCreated}"; } public string Delete() { var IsDeleted = _context.Database.EnsureDeleted(); return $"Create={IsDeleted}"; } } }
六、修改Views/Person/Create.cshtml,解决性别枚举类型无法列出枚举值的问题。
<select asp-for="Gender" asp-items="@Html.GetEnumSelectList(typeof(Gender))" class="form-control"></select>
七、修改StartUp.cs,增加配置文件读取
public static IConfiguration Config { get; set; } public static string CorpId { get { return Config.GetSection("CorpId").Value; } } public static string CorpSecret { get { return Config.GetSection("CorpSecret").Value; } } public static long DefaultDepartment { get { return int.Parse(Config.GetSection("DefaultDepartment").Value); } } public Startup(IConfiguration configuration) { Configuration = configuration; Config = configuration; }
八、添加微信操作类AccessToken.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Runtime.Serialization; using System.Runtime.Serialization.Json; using System.IO; using System.Text; namespace 信息采集系统.Common { public class AccessToken : JsonObject<AccessToken> { [DataMember] public int errcode { get; set; } [DataMember] public string errmsg { get; set; } [DataMember] public string access_token { get; set; } [DataMember] public int expires_in { get; set; } public static AccessToken Update() { var CorpId = Startup.CorpId; var Secret = Startup.CorpSecret; var url = $"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={CorpId}&corpsecret={Secret}"; var b = WebHelper.HttpGet(url); var item = AccessToken.From(b); return item; } } }
添加微信操作类QiYeWeiXinUser.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Runtime.Serialization; using System.Runtime.Serialization.Json; using System.IO; using System.Text; namespace 信息采集系统.Common { public class QiYeWeiXinUser { [DataContract] private class GetUserInfo : JsonObject<GetUserInfo> { [DataMember] public long errcode { get; set; } [DataMember] public string errmsg { get; set; } [DataMember] public string userid { get; set; } [DataMember] public string name { get; set; } [DataMember] public long[] department { get; set; } [DataMember] public string mobile { get; set; } [DataMember] public string gender { get; set; } [DataMember]public UserExtAttr extattr { get; set; } } [DataContract] private class AddUserRequest : JsonObject<AddUserRequest> { [DataMember] public string userid { get; set; } [DataMember] public string name { get; set; } [DataMember] public long[] department { get; set; } [DataMember] public string mobile { get; set; } [DataMember] public string gender { get; set; } [DataMember]public UserExtAttr extattr { get; set; } } [DataContract] public class AddUserResponse : JsonObject<AddUserResponse> { [DataMember] public long errcode { get; set; } [DataMember] public string errmsg { get; set; } } [DataContract] public class UserExtAttr { [DataMember]public List<UserAttr> attrs { get; set; } } [DataContract] public class UserAttr { [DataMember]public long type { get; set; } [DataMember]public string name { get; set; } [DataMember]public AttrText text { get; set; } } [DataContract] public class AttrText { [DataMember]public string value { get; set; } } public static bool Exist(string access_token, string userid) { var url = $"https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token={access_token}&userid={userid}"; var web = System.Net.WebRequest.Create(url); using (var responseStream = web.GetResponse().GetResponseStream()) { var sr = new System.IO.StreamReader(responseStream); var s = sr.ReadToEnd(); var b = System.Text.Encoding.UTF8.GetBytes(s); var item = GetUserInfo.From(b); if (item == null) { return false; } else { if (item.userid != userid) { return false; } else { return true; } } } } public static bool Add(string accesstoken, string userid, string name, string mobile, string gender, long[] department,string fatherName,string motherName, out string errmsg) { var user = new AddUserRequest() { userid = userid, name = name, mobile = mobile, gender = gender, department = department, extattr = new UserExtAttr() { attrs = new List<UserAttr>() { new UserAttr() { type = 0, name = "父亲", text = new AttrText() { value = fatherName } }, new UserAttr() { type = 0, name = "母亲", text = new AttrText() { value = motherName } } } } }; var b = user.ToArray(); var url = $"https://qyapi.weixin.qq.com/cgi-bin/user/create?access_token={accesstoken}"; var rb = WebHelper.HttpPost(url, b); var response = AddUserResponse.From(rb); if (response.errcode == 0) { errmsg = ""; return true; } else { errmsg = response.errmsg; return false; } } } }
九、修改PersonController.cs
public async Task<IActionResult> Create([Bind("ID,FullName,Gender,Mobile,InvitationCode")] Student student) { if (ModelState.IsValid) { #region 添加到企业微信 var pinyin = PinyinHelper.GetPinyin(student.FullName); var token = AccessToken.Update(); var index = 0; var userid = ""; var exist = true; while (exist) { if (index == 0) { userid = pinyin; } else { userid = $"{pinyin}{index}"; } exist = QiYeWeiXinUser.Exist(token.access_token, userid); } string errmsg; var success = QiYeWeiXinUser.Add(token.access_token, userid, student.FullName, student.Mobile, student.Gender.ToString(), new long[] { Startup.DefaultDepartment },out errmsg); Console.WriteLine($"add user:{student.FullName}\t{userid}"); #endregion if (success) { _context.Add(student); await _context.SaveChangesAsync(); //return RedirectToAction(nameof(Index)); return RedirectToAction(nameof(QRCode)); } else { return RedirectToAction(nameof(Error), new { errmsg }); } } return View(student); }
10、修改appsettings.json,增加以下内容
"CorpId": "wx8da1???????06720", "CorpSecret": "sc_LkWSzfKq2Y3x2??????????gMPlVtU5Ecx0zs", "DefaultDepartment": "3",