public IHttpActionResult Get(string code, string state) { bool checkResult = false; string fromQQ = Encryption.AesDecrypt(state); var tokenModel = githubConnector.AccessToken(code, ref checkResult); // 获取Access Token if (tokenModel != null) { if (!tokenModel.scope.Contains("repo") || tokenModel.scope == null) // 用户手动更改了权限,向用户返回权限不足信息 { CQ.Api.SendPrivateMessage(Convert.ToInt64(fromQQ), "抱歉,您申请的权限不足,绑定失败!"); return(BadRequest("权限不足")); } // 调用Github API获取用户数据 try { GithubUserInfo userInfo = githubConnector.GetUserInfo(tokenModel.access_token); // 用户信息 List <GithubRepositoryInfo> repositories = githubConnector.GetRepositories(tokenModel.access_token); // 授权用户的所有仓库信息 using (var context = new GithubWatcherContext()) { var user = context.GithubBindings.FirstOrDefault(s => s.GithubUserName == userInfo.Login); // 如果不存在,则往数据库中添加信息 if (user == null) { GithubBinding newBinding = new GithubBinding(); newBinding.QQ = fromQQ; newBinding.GithubUserName = userInfo.Login; newBinding.AccessToken = tokenModel.access_token; context.GithubBindings.Add(newBinding); CQ.Api.SendPrivateMessage(Convert.ToInt64(fromQQ), "绑定Github账户" + userInfo.Login + "成功!"); } else if (user.QQ == fromQQ) { if (user.AccessToken == tokenModel.access_token) { CQ.Api.SendPrivateMessage(Convert.ToInt64(fromQQ), "您已经绑定过该Github账户!"); } else { // 更新accessToken user.AccessToken = tokenModel.access_token; CQ.Api.SendPrivateMessage(Convert.ToInt64(fromQQ), "您已经绑定过该Github账户,已为您刷新Access Token,请尽快完成仓库绑定操作。"); } } else { CQ.Api.SendPrivateMessage(Convert.ToInt64(fromQQ), "抱歉,该Github账户已被其他用户绑定!"); } foreach (var repository in repositories) { var query = context.RepositoryInformations.FirstOrDefault(s => s.GithubUserName == userInfo.Login && s.Repository == repository.FullName); // 如果不存在,则往数据库中添加信息 if (query == null) { RepositoryInformation newRepositoryInfo = new RepositoryInformation(); newRepositoryInfo.GithubUserName = userInfo.Login; newRepositoryInfo.Repository = repository.FullName; context.RepositoryInformations.Add(newRepositoryInfo); } } context.SaveChanges(); return(Ok("绑定成功!")); } } catch (Exception e) { if (e.Message.Contains("基础连接已经关闭: 发送时发生错误")) { CQ.Api.SendPrivateMessage(Convert.ToInt64(fromQQ), "您的访问过于频繁,请稍后再试!"); } else { CQ.Api.SendPrivateMessage(Convert.ToInt64(fromQQ), "错误:" + e.Message + "请联系管理员QQ:2426837192!"); } return(BadRequest(e.Message)); } } return(BadRequest("获取Access Token失败!")); }