使用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 ...
随机推荐
- Java 04-基础 数据类型转换 自动类型转换+强制类型转换
1.数据类型自动转换 规则1:如果一个操作数为double型,则整个表达式提示至double型 规则2:满足自动类型转换条件, 两种类型要兼容,数值类型(整数和浮点)相互兼容 目标类型取值大于 ...
- 32.自定义Java异常捕获处理类及其使用
自定义异常捕获处理类 /** * <h1>异常捕捉</h1> * */ public class ExceptionHandler implements Thread.Unca ...
- vue 切换json语言包
1.在asstes文件夹新建 2.在main.js读取本地json语言包 3.在vue页面t这样引用
- golang中自带base64编码和解码
package main import ( "encoding/base64" "fmt" "log" ) func main() { in ...
- laravel ajax 实现省市区三级联动
首先将省市区的数据存储到数据库中 sql文件地址:http://m.caomeipi.com/ html <select name="province" style=&quo ...
- 肖sir__网页线下面试
第一题: 设计一下两个两位数相加的测试用例,说只能写数字不要写文字 第二题 淘宝订单怎么测试 功能测试: 1.测试订单输入的类型 2.测试金额数量:可创建等价类划分 3.测试库存数量变更 4.测试订单 ...
- redis in windows
Redis https://github.com/MSOpenTech/redis/releases 启动 redis-server redis.windows.conf 设置服务 redis-ser ...
- feign的工作原理
1.开发微服务时,我们会在微服务的主程序入口添加EnableFignClient注解开启对Feign Client扫描加载处理,根据FignClient接口规范,定义接口并加上FignClient注解 ...
- 解决“chrome正受到自动测试软件的控制”信息栏显示问题
在使用Selenium WebDriver启动谷歌浏览器Chrome时,在新启动的浏览器地址栏下方经常会显示一行提示信息:"chrome正受到自动测试软件的控制",英文的就是&qu ...
- pythonn全栈学习笔记--logging模块学习(四)
一.logging相关配置 1 import logging 2 """ 3 asctime:运行时间 4 name:主模块名称 5 levelname:日志级别 INF ...