使用ASP.NET Core开发信息采集系统将用户数据添加至企业微信
一、启动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",
使用ASP.NET Core开发信息采集系统将用户数据添加至企业微信的更多相关文章
- asp.net core系列 47 Identity 自定义用户数据
一.概述 接着上篇的WebAppIdentityDemo项目,将自定义用户数据添加到Identity DB,自定义扩展的用户数据类应继承IdentityUser类, 文件名为Areas / Ident ...
- [转]ASP.NET Core 开发-Logging 使用NLog 写日志文件
本文转自:http://www.cnblogs.com/Leo_wl/p/5561812.html ASP.NET Core 开发-Logging 使用NLog 写日志文件. NLog 可以适用于 . ...
- ASP.NET Core 开发-Logging 使用NLog 写日志文件
ASP.NET Core 开发-Logging 使用NLog 写日志文件. NLog 可以适用于 .NET Core 和 ASP.NET Core . ASP.NET Core已经内置了日志支持,可以 ...
- ASP.Net Core开发(踩坑)指南
ASP.NET与ASP.NET Core很类似,但它们之间存在一些细微区别以及ASP.NET Core中新增特性的使用方法,在此之前也写过一篇简单的对比文章ASP.NET MVC应用迁移到ASP.NE ...
- C# -- HttpWebRequest 和 HttpWebResponse 的使用 C#编写扫雷游戏 使用IIS调试ASP.NET网站程序 WCF入门教程 ASP.Net Core开发(踩坑)指南 ASP.Net Core Razor+AdminLTE 小试牛刀 webservice创建、部署和调用 .net接收post请求并把数据转为字典格式
C# -- HttpWebRequest 和 HttpWebResponse 的使用 C# -- HttpWebRequest 和 HttpWebResponse 的使用 结合使用HttpWebReq ...
- windows/Linux下设置ASP.Net Core开发环境并部署应用
10分钟学会在windows/Linux下设置ASP.Net Core开发环境并部署应用 创建和开发ASP.NET Core应用可以有二种方式:最简单的方式是通过Visual Studio 2017 ...
- ASP.NET Core 开发-中间件(Middleware)
ASP.NET Core开发,开发并使用中间件(Middleware). 中间件是被组装成一个应用程序管道来处理请求和响应的软件组件. 每个组件选择是否传递给管道中的下一个组件的请求,并能之前和下一组 ...
- ASP.NET Core开发-Docker部署运行
ASP.NET Core开发Docker部署,.NET Core支持Docker 部署运行.我们将ASP.NET Core 部署在Docker 上运行. 大家可能都见识过Docker ,今天我们就详细 ...
- ASP.NET Core开发-后台任务利器Hangfire使用
ASP.NET Core开发系列之后台任务利器Hangfire 使用. Hangfire 是一款强大的.NET开源后台任务利器,无需Windows服务/任务计划程序. 可以使用于ASP.NET 应用也 ...
- ASP.NET Core开发-读取配置文件Configuration
ASP.NET Core 是如何读取配置文件,今天我们来学习. ASP.NET Core的配置系统已经和之前版本的ASP.NET有所不同了,之前是依赖于System.Configuration和XML ...
随机推荐
- winform 登录后跳转百度地图报错 使用委托解决
最近用winform做一个登录后跳转到百度地图的小程序,使用了线程,winform的UI是单线程操作的,由于百度地图写在另外一个窗体,导致报错.后来使用了委托解决了这个小问题. delegate vo ...
- Jenkins自动化部署nodejs项目(前端项目)
1.安装nodejs插件 2.Linux系统安装nodejs (1)去nodejs官网下载最新包 https://nodejs.org/dist/latest/ (2)解压安装 tar xvzf no ...
- 1144. 递减元素使数组呈锯齿状 (Medium)
问题描述 1144. 递减元素使数组呈锯齿状 (Medium) 给你一个整数数组 nums,每次 操作 会从中选择一个元素并 将该元素的值减少 1. 如果符合下列情况之一,则数组 A 就是 锯齿数组: ...
- ORihard KCU116E: 经济实惠的 100Gbps 网络和存储 FPGA 开发平台
ORihard KCU116E: 经济实惠的 100Gbps 网络和存储 FPGA 开发平台 ORihard KCU116E: 经济实惠的 100Gbps 网络和存储 FPGA 开发平台 Kint ...
- ES6 新特性 ES6使用 超实用
ECMAScript 学习 ES5-数组的新方法 forEach forEach方法对数组的每个元素执行一次提供的函数.功能等同于for循环. 应用场景:为一些相同的元素,绑定事件处理器! var a ...
- virtualenv管理py环境linux版
因为服务器上已经安装了python3,所以直接安装virtualenv即可 pip3 install virtualenv -i https://mirrors.aliyun.com/pypi/sim ...
- sql中exists用法
exists关键字介绍 exists强调的是 是否返回结果集,不要求知道返回什么,比如: SELECT * FROM AM_USER WHERE EXISTS (SELECT 1 FROM AM_RO ...
- django学习:转载
https://www.cnblogs.com/ginvip/p/6894690.html https://www.cnblogs.com/yangmv/p/5327477.html https:// ...
- python编程中的if __name__ == 'main': 的作用
python的文件有两种使用的方法,第一是直接作为脚本执行,第二是import到其他的python脚本中被调用(模块重用)执行. 因此if __name__ == 'main': 的作用就是控制这两种 ...
- 打车起步价8元(3KM以内) 超过3KM,超出的每公里1.2元 超过5KM,超出的每公里1.5元 请在键盘上接收公里数,得出总价。
import java.util.Scanner; public class Taxi { public static void main(String []agrs){ Scanner s = ne ...