public ActionResult <BaseResponse> GetUserNav() { var user = _accountStoreService.QueryUserInfo(GetUserId()); var roles = new List <RoleDto>(); foreach (var role in user.UserRoleRelations) { var roleDto = _mapper.Map <RoleDto>(role.Role); roleDto.Routers = role.Role.RoleRouterRelations.Select(x => _mapper.Map <RouterDto>(x.Router)).Where(x => x.IsDelete == false).ToList(); roles.Add(roleDto); } List <RouterDto> routerList = new List <RouterDto>(); if (roles.Count > 0) { routerList = roles[0].Routers; //所有角色对应路由的并集 if (roles.Count > 1) { for (int i = 1; i < roles.Count; i++) { routerList = routerList.Union(roles[i].Routers).ToList(); } } routerList = routerList.OrderBy(x => x.Sort).ToList(); } return(BaseResponse <List <RouterDto> > .GetBaseResponse(routerList)); }
public ActionResult <BaseResponse> JobList(JobListRequest request) { var filters = new List <Expression <Func <JobEntity, bool> > >(); if (!string.IsNullOrWhiteSpace(request.Name)) { filters.Add(x => x.Name.Contains(request.Name) || x.Id.Contains(request.Name)); } if (request.Status >= 0) { filters.Add(x => x.Status == request.Status); } var result = _jobStore.QueryJobList(request.PageIndex, request.PageSize, filters, x => x.CreateTime, false, out int total); var pageData = new PageData <JobEntity>() { PageIndex = request.PageIndex, PageSize = request.PageSize, TotalCount = total, List = result }; return(BaseResponse <PageData <JobEntity> > .GetBaseResponse(pageData)); }
public ActionResult <BaseResponse> RefreshToken(RefreshTokenRequest request) { var jwtHandler = new JwtSecurityTokenHandler(); if (jwtHandler.CanReadToken(request.AccessToken)) { var jwt = new JwtSecurityTokenHandler().ReadJwtToken(request.AccessToken); var uId = jwt.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Sid)?.Value; if (!string.IsNullOrWhiteSpace(uId) && long.TryParse(uId, out long userId)) { var tokenCacheKey = CacheKey.Token(userId.ToString()); var token = _caching.Get <Token>(tokenCacheKey); if (token != null && token.RefreshToken == request.RefreshToken) { var user = _accountStoreService.QueryUserById(userId); if (user != null) { var newToken = GenerateToken(user); token.AccessToken = newToken.AccessToken; token.AccessTokenExpires = newToken.AccessTokenExpires; var refreshTokenExpires = FormatHelper.ConvertToDateTime(token.RefreshTokenExpires); var expireTimeSpan = refreshTokenExpires - DateTime.Now; _caching.Set(tokenCacheKey, token, expireTimeSpan); return(BaseResponse <Token> .GetBaseResponse(token)); } } } } return(BaseResponse.GetBaseResponse(ResponseStatusType.Unauthorized, "刷新失败")); }
public ActionResult <BaseResponse> QueryPermissionList(PermissionListRequest request) { var routerList = _mapper.Map <List <RouterDto> >(_accountStoreService.QueryRouterList()); long total = 0; List <RouterDto> result = new List <RouterDto>(); if (!string.IsNullOrWhiteSpace(request.Name)) { routerList = routerList.Where(x => x.Name.Contains(request.Name) || x.Title.Contains(request.Name)).ToList(); total = routerList.Count(); result = routerList.OrderBy(x => x.Sort).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList(); } else { total = routerList.Where(x => x.ParentId == 0).Count(); result = routerList.Where(x => x.ParentId == 0).OrderBy(x => x.Sort).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList(); result.ForEach(item => { item.Children = routerList.ConvertToTree <long, RouterDto>(item.Id); }); } var pageData = new PageData <RouterDto>() { PageIndex = request.PageIndex, PageSize = request.PageSize, TotalCount = total, List = result }; return(BaseResponse <PageData <RouterDto> > .GetBaseResponse(pageData)); }
public async Task <BaseResponse> MockAsy() { User user = new User { UserName = "******", UserAccount = "1233123213123", UserPassWord = "******", CertificateNo = "123131", Mobile = 13313331333, IsVerify = IsVerifyEnum.可用 }; _userRepository.Insert(user); var a = await _userRepository.SaveChangesAsync(); //这里故意增加这个判断,为了测试mock if (a > 0) { return(BaseResponse.GetBaseResponse(BusinessStatusType.OK)); } else { return(BaseResponse.GetBaseResponse(BusinessStatusType.Failed)); } }
public ActionResult <BaseResponse> QueryUserList(UserListRequest request) { var filters = new List <Expression <Func <User, bool> > >(); if (!string.IsNullOrWhiteSpace(request.Name)) { filters.Add(x => x.Name.Contains(request.Name)); } if (request.Status > 0) { filters.Add(x => x.Status == request.Status); } var result = _accountStoreService.QueryUserListPage(request.PageIndex, request.PageSize, filters, x => x.CreateTime, false, out int total); var list = new List <UserDto>(); foreach (var user in result) { var userDto = _mapper.Map <UserDto>(user); userDto.Roles = user.UserRoleRelations.Select(x => _mapper.Map <RoleDto>(x.Role)).Where(x => x.IsDelete == false).OrderBy(x => x.CreateTime).ToList(); list.Add(userDto); } var pageData = new PageData <UserDto>() { PageIndex = request.PageIndex, PageSize = request.PageSize, TotalCount = total, List = list }; return(BaseResponse <PageData <UserDto> > .GetBaseResponse(pageData)); }
public async Task <BaseResponse> SendMessageById([FromBody] PushMessageRequest request) { if (!MessageHub.connections.ContainsKey(request.ReceivedUserId.ToString())) { return(BaseResponse.GetBaseResponse(BusinessStatusType.LoginExpire)); } return(await _messageSer.SendMessageById(request)); }
private JsonResult GenerateJsonResult(string message) { var data = BaseResponse.GetBaseResponse(BusinessStatusType.ParameterError, message); return(new JsonResult(data) { StatusCode = 200 }); }
public ActionResult <BaseResponse> Info() { var user = _accountStoreService.QueryUserInfo(GetUserId()); var userDto = _mapper.Map <UserDto>(user); var roles = user.UserRoleRelations.Select(x => _mapper.Map <RoleDto>(x.Role)).ToList(); return(BaseResponse <UserInfoResponse> .GetBaseResponse(new UserInfoResponse() { User = userDto, Roles = roles })); }
private Task HandleExceptionAsync(HttpContext context, Exception ex, string body) { string errorMsg = ex.Source + "\n" + ex.StackTrace + "\n" + ex.Message + "\n" + ex.InnerException; WriteErrorLog(context, ex, body); PathString path = context.Request.Path; var data = BaseResponse.GetBaseResponse(BusinessStatusType.Error); var result = JsonConvert.SerializeObject(data); context.Response.ContentType = "application/json;charset=utf-8"; return(context.Response.WriteAsync(result)); }
public void OnException(ExceptionContext context) { var controller = context.RouteData.Values["controller"]; var action = context.RouteData.Values["action"]; var path = context.HttpContext.Request.Path; var queryString = context.HttpContext.Request.QueryString.Value; _log.Error($"[url]:{path + queryString}\r\n[controller]:{controller}\r\n[action]:{action}", context.Exception); context.ExceptionHandled = true; context.Result = new JsonResult(BaseResponse.GetBaseResponse(ResponseStatusType.ServerException)); }
public async Task <BaseResponse> TestAsy() { //using (var transaction =await _zsPiccCallRepository.GetDbContext().Database.BeginTransactionAsync()) //{ // User user = new User // { // UserName = "******", // UserAccount = "1233123213123", // UserPassWord = "******", // CertificateNo = "123131", // Mobile = 13313331333, // IsVerify = IsVerifyEnum.可用 // }; // await _userRepository.InsertAsync(user); // await _userRepository.GetDbContext().Database.ExecuteSqlCommandAsync(new RawSqlString(" delete from user where user.Id=8")); // await _zsPiccCallRepository.SaveChangesAsync(); // transaction.Commit(); //} //var list = await _dataExcelRepository.GetAllListAsync(); //if (userThis == null) //{ // return BaseResponse.GetBaseResponse(BusinessStatusType.Failed, "发起请求的用户不存在"); //} //UserDto userDto = _mapper.Map<UserDto>(userThis); //List<ZsPiccCall> piccList=new List<ZsPiccCall>(); //foreach (var item in list) //{ // ZsPiccCall picc = _mapper.Map<ZsPiccCall>(item); // picc.CallPassword = picc.CallPassword.Substring(0, picc.CallPassword.Length - 2); // picc.CallExtNumber = picc.CallExtNumber.Substring(0, picc.CallExtNumber.Length - 2); // picc.CallNumber = picc.CallNumber.Substring(0, picc.CallNumber.Length - 2); // picc.CallId = 0; // picc.UserAgentId = 0; // picc.CallState = 1; // picc.CreateTime = DateTime.Now; // picc.UpdateTime = DateTime.Now; // _zsPiccCallRepository.Insert(picc); //} //_zsPiccCallRepository.SaveChanges(); //return new BaseResponse(BusinessStatusType.OK); return(BaseResponse.GetBaseResponse(BusinessStatusType.OK)); //string a = "{ 'UserId':'10'}"; //string url = $"{_urlModel.BihuApi}/api/Message/MessageExistById"; //string result = await HttpWebAsk.HttpClientPostAsync(a, url); }
public async Task <BaseResponse> AsyncIoExcelFile() { string url = "http://image.91bihu.com//images/2019/3/12/user/de51f32e-60be-439f-9f17-a6e3302e1db7.xls"; try { string storePath = "E:\\test.xlsx"; string tempPath = Path.GetDirectoryName(storePath); Directory.CreateDirectory(tempPath); //创建临时文件目录 string tempFile = tempPath + @"\" + Path.GetFileName(storePath) + ".temp"; //临时文件 if (File.Exists(tempFile)) { File.Delete(tempFile); //存在则删除 } if (File.Exists(storePath)) { File.Delete(storePath); //存在则删除 } LogHelper.Info("创建临时文件:" + tempFile); FileStream fs = new FileStream(tempFile, FileMode.Append, FileAccess.Write, FileShare.ReadWrite, 1024, FileOptions.Asynchronous); // 设置参数 HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; //发送请求并获取相应回应数据 HttpWebResponse response = request.GetResponse() as HttpWebResponse; //直到request.GetResponse()程序才开始向目标网页发送Post请求 Stream responseStream = response.GetResponseStream(); //创建本地文件写入流 //Stream stream = new FileStream(tempFile, FileMode.Create); byte[] bArr = new byte[1024]; int size = responseStream.Read(bArr, 0, (int)bArr.Length); while (size > 0) { //stream.Write(bArr, 0, size); await fs.WriteAsync(bArr, 0, size); size = responseStream.Read(bArr, 0, (int)bArr.Length); } fs.Close(); responseStream.Close(); LogHelper.Info("移动临时文件到指定位置开始:" + storePath); File.Move(tempFile, storePath); LogHelper.Info("移动临时文件到指定位置完成:" + storePath); } catch (Exception ex) { LogHelper.Error("读取批量续保文件路径" + url + " 错误信息:" + ex.Message); } return(BaseResponse.GetBaseResponse(BusinessStatusType.OK)); }
private Task HandleExceptionAsync(HttpContext context, Exception ex, string body) { WriteErrorLog(context, ex, body); //Stream stream = context.Items["Stream"] as Stream; //context.Response.Body = stream; var data = BaseResponse.GetBaseResponse(BusinessStatusType.Error); var result = JsonConvert.SerializeObject(data); context.Response.StatusCode = 500; context.Response.ContentType = "application/json;charset=utf-8"; //LogHelper.Info(context.Items["LogString"] + Environment.NewLine + "请求返回值:请求出现异常"); return(context.Response.WriteAsync(result)); }
/// <summary> /// 进行消息推送 /// </summary> /// <param name="request"></param> /// <returns></returns> public async Task <BaseResponse> SendMessageById(PushMessageRequest request) { MessageViewModel thisMessage = JsonConvert.DeserializeObject <MessageViewModel>(JsonConvert.SerializeObject(request)); List <MessageViewModel> messageList = new List <MessageViewModel> { thisMessage }; string content = JsonConvert.SerializeObject(messageList); _logger.LogInformation("系统消息已发送ID:" + request.ReceivedUserId + "内容:" + content); await _hubcontext.Clients.Client(MessageHub.connections[request.ReceivedUserId.ToString()]).SendAsync("sendMessage", content); return(BaseResponse.GetBaseResponse(BusinessStatusType.OK)); }
public ActionResult <BaseResponse> Login(LoginRequest request) { //admin 123456 var user = _accountStoreService.QueryUserByName(request.Username); if (user == null) { return(BaseResponse.GetBaseResponse(ResponseStatusType.Failed, "用户名错误")); } if (user.Password != request.Password) { return(BaseResponse.GetBaseResponse(ResponseStatusType.Failed, "密码错误")); } var tokenCacheKey = CacheKey.Token(user.Id.ToString()); var token = _caching.Get <Token>(tokenCacheKey); if (token == null) { //新登录用户 创建新Token token = GenerateToken(user); _caching.Set(tokenCacheKey, token, TimeSpan.FromDays(_jwtConfig.RefreshTokenExpiresDays)); } else { //老用户 var expires = FormatHelper.ConvertToDateTime(token.AccessTokenExpires); if (expires <= DateTime.Now) { //AccessTokeng过期 重新生成 var newToken = GenerateToken(user); //只更新AccessToken,老的RefreshToken保持不变 token.AccessToken = newToken.AccessToken; token.AccessTokenExpires = newToken.AccessTokenExpires; var refreshTokenExpires = FormatHelper.ConvertToDateTime(token.RefreshTokenExpires); var expireTimeSpan = refreshTokenExpires - DateTime.Now; _caching.Set(tokenCacheKey, token, expireTimeSpan); } } UpdateLastLoginInfo(user); return(BaseResponse <Token> .GetBaseResponse(token)); }
public ActionResult <BaseResponse> QueryPermissionTreeList() { var routerList = _mapper.Map <List <RouterDto> >(_accountStoreService.QueryRouterList()); List <TreeData> list = routerList.OrderBy(x => x.Sort).Select(x => new TreeData() { Title = x.Title, Value = x.Id, Key = x.Id, ParentId = x.ParentId }).ToList(); TreeData tree = new TreeData() { Title = "根目录", Value = 0, Key = 0, Children = list.ConvertToTree <long, TreeData>(0) }; return(BaseResponse <List <TreeData> > .GetBaseResponse(new List <TreeData>() { tree })); }
public async Task <BaseResponse> DelAllSheet(BaseRequest request) { using (TransactionScope ts = new TransactionScope()) { User user = _userRepository.FirstOrDefault(c => c.Id == request.UserId); if (user == null) { return(BaseResponse.GetBaseResponse(BusinessStatusType.OK)); } _userRepository.Delete(user); await _userRepository.SaveChangesAsync(); _delAllSheetObserver(request.UserId); ts.Complete(); } return(BaseResponse.GetBaseResponse(BusinessStatusType.OK)); }
public async Task <BaseResponse> AsyncIoExcel() { string url = "http://image.91bihu.com/images/2019/3/12/user/de51f32e-60be-439f-9f17-a6e3302e1db7.xls"; try { string storePath = "E:\\test.xlsx"; string tempPath = Path.GetDirectoryName(storePath); Directory.CreateDirectory(tempPath); //创建临时文件目录 string tempFile = tempPath + @"\" + Path.GetFileName(storePath) + ".temp"; //临时文件 if (File.Exists(tempFile)) { File.Delete(tempFile); //存在则删除 } if (File.Exists(storePath)) { File.Delete(storePath); //存在则删除 } LogHelper.Info("创建临时文件:" + tempFile); FileStream fs = new FileStream(tempFile, FileMode.Append, FileAccess.Write, FileShare.ReadWrite, 1024, FileOptions.Asynchronous); using (var httpClient = new HttpClient()) { var response = await httpClient.GetAsync(url); var buffer = await response.Content.ReadAsByteArrayAsync(); await fs.WriteAsync(buffer, 0, buffer.Length); } fs.Close(); LogHelper.Info("移动临时文件到指定位置开始:" + storePath); File.Move(tempFile, storePath); LogHelper.Info("移动临时文件到指定位置完成:" + storePath); } catch (Exception ex) { LogHelper.Error("读取批量续保文件路径" + url + " 错误信息:" + ex.Message); } return(BaseResponse.GetBaseResponse(BusinessStatusType.OK)); }
public async Task <ActionResult <BaseResponse> > ServiceList(ServiceListRequest request) { var services = await _serviceRoute.QueryServices(); if (!string.IsNullOrWhiteSpace(request.Name)) { services = services.Where(x => x.Name.Contains(request.Name)); } var total = services.Count(); var result = services.ToList().Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList(); var pageData = new PageData <ServiceRouteDescriptor>() { PageIndex = request.PageIndex, PageSize = request.PageSize, TotalCount = total, List = result }; return(BaseResponse <PageData <ServiceRouteDescriptor> > .GetBaseResponse(pageData)); }
public async Task <BaseResponse> AddUserByAccount(AddUserByAccountRequest request) { if (_strDic.ContainsKey(request.Account)) { return(BaseResponse.GetBaseResponse(BusinessStatusType.Failed, "键值已存在")); } //成功写入 if (_strDic.TryAdd(request.Account, request.Account)) { LogHelper.Info("成功写入"); var userExist = await _userRepository.FirstOrDefaultAsync(c => c.UserAccount == request.Account); if (userExist == null) { LogHelper.Info("新增账户:" + request.Account); User user = new User { UserName = "******", UserPassWord = "******", CertificateNo = "123131", Mobile = 13313331333, IsVerify = IsVerifyEnum.可用 }; user.UserAccount = request.Account; _userRepository.Insert(user); _userRepository.SaveChanges(); } string res; if (_strDic.TryRemove(request.Account, out res)) { LogHelper.Info("去除成功"); } return(BaseResponse.GetBaseResponse(BusinessStatusType.OK)); } //尝试竞争线程,写入失败 return(BaseResponse.GetBaseResponse(BusinessStatusType.Failed, "写入失败")); }
public async Task <BaseResponse> AddUserAllSheet() { User user = new User { UserName = "******", UserPassWord = "******", CertificateNo = "123131", UserAccount = "123", Mobile = 13313331333, IsVerify = IsVerifyEnum.可用 }; _userRepository.Insert(user); //这里需要id,所以必须保存一下 await _userRepository.SaveChangesAsync(); UserExtent userExtent = new UserExtent { UserId = user.Id, UserHobby = "123123", UserOccupation = "123131", }; _userExtentReopsitory.Insert(userExtent); UserConfig userConfig = new UserConfig { UserId = user.Id, UserLevel = 123, UserGrade = 123, }; _userConfigRepository.Insert(userConfig); await _userConfigRepository.SaveChangesAsync(); return(BaseResponse.GetBaseResponse(BusinessStatusType.OK)); }
public ActionResult <BaseResponse> Logout() { _caching.Remove(CacheKey.Token(GetUserId().ToString())); return(BaseResponse.GetBaseResponse(ResponseStatusType.Success)); }
public async Task <BaseResponse> RoleModuleByRoleIdAsync([FromBody] RoleModuleByRoleIdRequest request) { return(BaseResponse <List <ModuleTreeViewModel> > .GetBaseResponse(BusinessStatusType.OK, await _roleService.RoleModuleByRoleIdAsync(request.RoleId, request.CompId))); }
public async Task <ActionResult <BaseResponse> > UploadPackage() { var files = Request.Form.Files; var response = new List <UploadPackageResponse>(); foreach (var file in files) { var result = new UploadPackageResponse(); var uploadPath = ""; try { var fileExtension = Path.GetExtension(file.FileName); if (!_allowedFileExtension.Contains(fileExtension, StringComparer.OrdinalIgnoreCase)) { result.Success = false; result.ErrorMessage = "后缀不支持"; response.Add(result); continue; } result.FileName = $"{Path.GetFileNameWithoutExtension(file.FileName)}{DateTime.Now.FormatString("yyyyMMddHHmmss")}{fileExtension}"; var uploadDirectory = Path.Combine(_hostEnvironment.ContentRootPath, _jobDirectory); if (!Directory.Exists(uploadDirectory)) { Directory.CreateDirectory(uploadDirectory); } uploadPath = Path.Combine(uploadDirectory, result.FileName); var webPath = string.Concat("/", _jobDirectory, "/", result.FileName); using (var fileStream = new FileStream(uploadPath, FileMode.Create)) { await file.CopyToAsync(fileStream); result.Success = true; result.Url = webPath; } } catch (Exception ex) { _logger.LogError(ex, $"{file.FileName} {file.ContentType}"); result.Success = false; result.ErrorMessage = ex.Message; } response.Add(result); if (result.Success) { var services = await _serviceRoute.QueryServices(); foreach (var service in services) { if (service.Name == "worker") { await _schedulerRemoting.UploadFile(uploadPath, service); } } } } return(BaseResponse <List <UploadPackageResponse> > .GetBaseResponse(response)); }
public async Task <BaseResponse> TestPost() { return(BaseResponse.GetBaseResponse(BusinessStatusType.OK, await _messageSer.MessageShorById("105"))); //return await Task.Run(() => { return BaseResponse.GetBaseResponse(BusinessStatusType.OK); }); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { #region 模型、仓储和service注入及其他细节 services.RegisterAssembly("CronJobsMysql", Lifecycle.Scoped); //services.AddAutoMapper(); 这里使用另一种automapper的注入方式 IConfigurationProvider config = new MapperConfiguration(cfg => { cfg.AddProfile <DtoProfile>(); }); services.AddSingleton(config); services.AddScoped <IMapper, Mapper>(); #endregion #region mysql services.AddScoped <DbContext, CronJobsMysqlContext>(); #endregion #region 定时任务注册 services.AddHostedService <QuartzService>(); services.AddScoped <JobCronTrigger>(); #endregion #region MVC //AddControllersWithViews 是mvc项目使用 api可以直接AddControllers services.AddControllersWithViews() .AddJsonOptions(options => { options.JsonSerializerOptions.Converters.Add(new DateTimeConverter()); options.JsonSerializerOptions.Encoder = JavaScriptEncoder.Create(UnicodeRanges.All); }) .ConfigureApiBehaviorOptions(options => { //options.SuppressModelStateInvalidFilter = true; options.InvalidModelStateResponseFactory = context => { var validationErrors = context.ModelState .Keys .SelectMany(k => context.ModelState[k].Errors) .Select(e => e.ErrorMessage) .ToArray(); var json = BaseResponse.GetBaseResponse(BusinessStatusType.ParameterError, string.Join(",", validationErrors)); return(new BadRequestObjectResult(json) { ContentTypes = { "application/problem+json" } }); }; }); services.AddHttpClient(); services.AddHttpContextAccessor(); services.AddCors(options => { options.AddPolicy("CorsPolicy", builder => builder.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader() //如果把下面的也允许就会报错 //.AllowCredentials() ); }); #endregion }
// This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { #region MVC //AddControllersWithViews 是mvc项目使用 api可以直接AddControllers services.AddControllersWithViews(options => { // 异常处理 使用中间件的异常处理吧 //options.Filters.Add(typeof(HttpGlobalExceptionFilter<Exception>)); }) .AddJsonOptions(options => { //options.JsonSerializerOptions.Converters.Add(new DateTimeConverter()); options.JsonSerializerOptions.Encoder = JavaScriptEncoder.Create(UnicodeRanges.All); }) .ConfigureApiBehaviorOptions(options => { //options.SuppressModelStateInvalidFilter = true; options.InvalidModelStateResponseFactory = context => { var validationErrors = context.ModelState .Keys .SelectMany(k => context.ModelState[k].Errors) .Select(e => e.ErrorMessage) .ToArray(); var json = BaseResponse.GetBaseResponse(BusinessStatusType.ParameterError, string.Join(",", validationErrors)); return(new BadRequestObjectResult(json) { ContentTypes = { "application/problem+json" } }); }; }); services.AddHttpClient(); services.AddHttpContextAccessor(); //services.AddCors(options => //{ // options.AddPolicy("CorsPolicy", // builder => builder.AllowAnyOrigin() // .WithMethods("GET", "POST", "HEAD", "PUT", "DELETE", "OPTIONS") // ); //}); services.AddCors(options => { options.AddPolicy("CorsPolicy", builder => builder.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader() //.WithMethods("GET", "POST", "HEAD", "PUT", "DELETE", "OPTIONS") //如果把下面的也允许就会报错 //.AllowCredentials() ); }); #endregion #region Authentication JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(options => { options.Events = new JwtBearerEvents() { OnChallenge = async context => { //var data = new BaseResponse(BusinessStatusType.Unauthorized); //var result = JsonConvert.SerializeObject(data); var result = " {\"code\":401,\"message\":\"授权失败\",\"data\":null}"; //会报StatusCode cannot be set because the response has already started. //context.Response.StatusCode = 401; context.Response.ContentType = "application/json;charset=utf-8"; await context.Response.WriteAsync(result); }, OnMessageReceived = context => { var accessToken = context.Request.Query["access_token"]; // If the request is for our hub... var path = context.HttpContext.Request.Path; if (!string.IsNullOrEmpty(accessToken) && (path.StartsWithSegments("/bihuHub"))) { // Read the token out of the query string context.Token = accessToken; } return(Task.CompletedTask); } }; options.Authority = SettingManager.GetValue("Authority"); options.RequireHttpsMetadata = false; options.Audience = "employee_center"; //options.TokenValidationParameters.ValidIssuer = "null"; options.TokenValidationParameters.ValidateIssuer = false; options.TokenValidationParameters.ValidateIssuerSigningKey = false; options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters { ClockSkew = TimeSpan.FromMinutes(30) }; }); #endregion #region SignalR services.AddSignalR(); services .AddSignalR() .AddStackExchangeRedis(SettingManager.GetValue("SignalrStoreConnectionString"), options => { options.Configuration.ChannelPrefix = "bihuHub"; }); #endregion #region DataProtection密钥共享 //cookies 密钥共享,可以用redis 也可以是同一个xml文件 这里我用redis //services.AddSingleton<IXmlRepository, CustomFileXmlRepository>(); //services.AddDataProtection(configure => //{ // configure.ApplicationDiscriminator = "bihuHub"; //}); //建立Redis 连接 ConnectionMultiplexer redis = ConnectionMultiplexer.Connect(SettingManager.GetValue("SignalrStoreConnectionString")); services.AddSingleton(redis); //添加数据保护服务,设置统一应用程序名称,并指定使用Reids存储私钥 services.AddDataProtection() .SetApplicationName(Assembly.GetExecutingAssembly().FullName) .PersistKeysToStackExchangeRedis(redis, "DataProtection-Keys"); #endregion #region Rabbitmq services.AddRabbitmq(); ConfigureRabbitMqClient(services); #endregion }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.Configure <JWTConfig>(Configuration.GetSection("JWTConfig")); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.Events = new JwtBearerEvents { OnTokenValidated = TokenValidatedFilter.OnTokenValidated }; options.TokenValidationParameters = new TokenValidationParameters { ValidIssuer = Configuration.GetValue <string>("JWTConfig:Issuer"), ValidAudience = Configuration.GetValue <string>("JWTConfig:Audience"), IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration.GetValue <string>("JWTConfig:IssuerSigningKey"))) }; }); services.AddControllers() .AddJsonOptions(options => { options.JsonSerializerOptions.Converters.Add(new DateTimeConverter()); }) .ConfigureApiBehaviorOptions(options => { options.InvalidModelStateResponseFactory = context => { var error = context.ModelState.GetValidationSummary(); return(new JsonResult(BaseResponse <List <ModelState> > .GetBaseResponse(ResponseStatusType.ParameterError, error))); }; }); services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); //Swagger services.AddSwaggerGen(options => { options.SwaggerDoc("v1", new OpenApiInfo { Version = "v1", Title = "SchedulerZ.Manager API", Description = "A Simple SchedulerZ.Manager Web API" }); //options.OperationFilter<SwaggerOperationFilter>(); var basePath = Path.GetDirectoryName(typeof(Program).Assembly.Location); options.IncludeXmlComments(Path.Combine(basePath, "SchedulerZ.Manager.API.xml")); options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme { Description = "JWT Authorization header using the Bearer scheme.", Name = "Authorization", In = ParameterLocation.Header, Scheme = "bearer", Type = SecuritySchemeType.Http, BearerFormat = "JWT" }); options.AddSecurityRequirement(new OpenApiSecurityRequirement { { new OpenApiSecurityScheme { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" } }, new List <string>() } }); }); //Origin services.AddCors(options => { options.AddPolicy("AllowAllOrigins", builder => { builder.AllowAnyOrigin().AllowAnyHeader(); }); }); services.UseSchedulerZ() .UseMySQL() .UseRedisCache() .UseConsulServiceRoute() .UseGrpcRemotingClient(); }
public BaseResponse OldRoleModuleByRoleId([FromBody] RoleModuleByRoleIdRequest request) { var a = _roleService.OldRoleModuleByRoleId(request.RoleId, request.CompId); return(BaseResponse <object> .GetBaseResponse(BusinessStatusType.OK, a)); }