public IActionResult CategoryOne(string id) { Models.ItemViewModel itemModel = new ItemViewModel(); if (id != null) { itemModel.Id = id; itemModel.Name = "Fishes"; itemModel.Provider = "FishProvider"; itemModel.SubCategory = "Fantasy"; var currentHttpContext = new CurrentHttpContext(HttpContext); itemModel.LogoUrl = Url.Content("~/images/examples/lots-of-fish-639x470.jpg"); //Path.Combine(currentHttpContext.GetBaseUrl(), "images", "examples", "lots-of-fish-639x470.jpg"); //+ Url.Content("~/images/lots-of-fish-639x470.jpg"); itemModel.AgeCategory = 12; itemModel.Price = 50.02M; return(View("CategoryOne", itemModel)); } return(View("CategoryOne")); }
/// <summary> /// Выполнить вход в систему /// </summary> /// <param name="login">Имя входа пользователя</param> public async Task PerformLogin(string login) { const string NameType = ClaimsIdentity.DefaultNameClaimType; const string RoleType = ClaimsIdentity.DefaultRoleClaimType; // Выполнение входа var userClaims = new List <Claim>() { new Claim(NameClaimType, login), new Claim(RoleClaimType, DefaultRole) }; var id = new ClaimsIdentity(userClaims, AuthScheme, NameType, RoleType); await CurrentHttpContext.SignInAsync(AuthScheme, new ClaimsPrincipal(id)); // Записать в данные сеанса Session.SetString(SessionLoginKey, login); }
public async Task <IHttpActionResult> Post(TaskRequest request) { Logger.InfoFormat("Received task {taskJson}", request.TaskJson); TaskBase taskObject = request.TaskJson.FromJson <TaskBase>(); // check error rate string cacheKey = $"error-rate:{taskObject.GetType().Name}"; if (CurrentHttpContext.Instance().Cache.Get(cacheKey) is not RateLimit cacheItem) { // allow 1 error per hour cacheItem = RateLimit.Create(cacheKey, 1, 1, 3600); CurrentHttpContext.Instance().Cache.Insert( cacheKey, cacheItem, null, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.Default, (key, item, reason) => Logger.InfoFormat( "cache item '{key}' removed due to '{reason}'", key, reason)); } _ = cacheItem.UpdateAllowance(DateTime.Now); if (cacheItem.Allowance < 1) { Logger.InfoFormat( "throttling {cacheKey} due to allowance = {allowance}", cacheKey, cacheItem.Allowance.ToString("N2")); return(Ok( $"throttled due to unhandled exception (allowance = {cacheItem.Allowance:N2})")); } IDisposable scope = NLog.NestedDiagnosticsLogicalContext.Push(taskObject.BusinessKey); try { Logger.Info("begin"); IHttpActionResult result = await Transact <IHttpActionResult>(async databases => { // check for published task PublishedTask?publishedTask = await databases.Snittlistan.PublishedTasks.SingleOrDefaultAsync( x => x.MessageId == request.MessageId); if (publishedTask is null) { return(BadRequest($"no published task found with message id {request.MessageId}")); } if (publishedTask.HandledDate.HasValue) { return(Ok($"task with message id {publishedTask.MessageId} already handled")); } bool handled = await HandleMessage( taskObject, request.CorrelationId ?? default, request.MessageId ?? default, databases); if (handled) { publishedTask.MarkHandled(DateTime.Now); } return(Ok()); }); return(result); } catch (Exception ex) { Logger.WarnFormat( ex, "decreasing allowance for {cacheKey}", cacheKey); _ = cacheItem.DecreaseAllowance(); throw; } finally { Logger.Info("end"); scope.Dispose(); } }
public void ClearError() { CurrentHttpContext.ClearError(); }
public void RewritePath(string path, string queryString) { logger.Debug("Rewriting '" + Url.LocalUrl + "' to '" + path + "'"); CurrentHttpContext.RewritePath(path, "", queryString); }
public void RewritePath(string path) { logger.Debug("Rewriting '" + Url.LocalUrl + "' to '" + path + "'"); CurrentHttpContext.RewritePath(path, false); }
public async Task Handle(HandlerContext <TCommand> context) { (string key, int rate, int perSeconds) = GetRate(context); // check cache if (CurrentHttpContext.Instance().Cache.Get(key) is not RateLimit cacheItem) { cacheItem = RateLimit.Create(key, 1, rate, perSeconds); Logger.InfoFormat( "add {key} to cache: {@cacheItem}", key, cacheItem); CurrentHttpContext.Instance().Cache.Insert( key, cacheItem, null, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.Default, (key, item, reason) => Logger.InfoFormat( "cache item '{key}' removed due to '{reason}'", key, reason)); } // check database KeyValueProperty?rateLimitProperty = await CompositionRoot.Databases.Snittlistan.KeyValueProperties .SingleOrDefaultAsync(x => x.Key == key); if (rateLimitProperty == null) { KeyValueProperty keyValueProperty = new( context.Tenant.TenantId, key, RateLimit.Create(key, 1, rate, perSeconds)); rateLimitProperty = CompositionRoot.Databases.Snittlistan.KeyValueProperties.Add(keyValueProperty); } else { rateLimitProperty.ModifyValue <RateLimit>( r => r.SetRate(rate).SetPerSeconds(perSeconds), x => Logger.InfoFormat("before: {@x}", x), x => Logger.InfoFormat("after: {@x}", x)); } DateTime now = DateTime.Now; rateLimitProperty.ModifyValue <RateLimit>( x => x.UpdateAllowance(now), x => Logger.InfoFormat("before: {@x}", x), x => Logger.InfoFormat("after: {@x}", x)); _ = cacheItem.UpdateAllowance(now); double allowance = rateLimitProperty.GetValue <RateLimit, double>(x => x.Allowance); if (allowance < 1 || cacheItem.Allowance < 1) { string message = $"(db) allowance = {allowance:N2}, (cache) allowance = {cacheItem.Allowance:N2}, wait to reach 1"; throw new HandledException(message); } TEmail email = await CreateEmail(context); EmailState state = email.State; _ = CompositionRoot.Databases.Snittlistan.SentEmails.Add(new( email.From, email.To, email.Bcc, email.Subject, state)); Logger.InfoFormat("sending email {@email}", email); await CompositionRoot.EmailService.SendAsync(email); rateLimitProperty.ModifyValue <RateLimit>( x => x.DecreaseAllowance(), x => Logger.InfoFormat("before: {@x}", x), x => Logger.InfoFormat("after: {@x}", x)); _ = cacheItem.DecreaseAllowance(); }
/// <summary> /// Выполнить выход из системы /// </summary> public async Task PerformLogout() { await CurrentHttpContext.SignOutAsync(); Session.Clear(); }
public void Configure(IApplicationBuilder app) { app.UseDeveloperExceptionPage(); app.UseStatusCodePages(); app.UseStaticFiles(); app.UseIdentity(); app.UseMvc(routes => { routes.MapRoute( name: null, template: "{categoryId:int}/{page:int}", defaults: new { controller = "Blog", action = "Index" } ); routes.MapRoute( name: null, template: "{page:int}", defaults: new { controller = "Blog", action = "Index", page = 1 } ); routes.MapRoute( name: null, template: "{categoryId:int}", defaults: new { controller = "Blog", action = "Index", page = 1 } ); routes.MapRoute( name: null, template: "user/new", defaults: new { controller = "Account", action = "SignUp" } ); routes.MapRoute( name: null, template: "user/in", defaults: new { controller = "Account", action = "Login" } ); routes.MapRoute( name: null, template: "user/out", defaults: new { controller = "Account", action = "Logout" } ); routes.MapRoute( name: null, template: "profile/{page:int}", defaults: new { controller = "Blog", action = "MyPage", page = 1 } ); routes.MapRoute( name: null, template: "blogs", defaults: new { controller = "Blog", action = "Index" } ); routes.MapRoute( name: null, template: "blog/{blogId:int}", defaults: new { controller = "Blog", action = "ViewBlog" } ); routes.MapRoute( name: null, template: "users/{page:int}", defaults: new { controller = "UserAdmin", action = "Index", page = 1 } ); routes.MapRoute( name: null, template: "users/new", defaults: new { controller = "UserAdmin", action = "Create" } ); routes.MapRoute( name: null, template: "users/delete/{id:required}", defaults: new { controller = "UserAdmin", action = "Delete" } ); routes.MapRoute( name: null, template: "users/edit/{id:required}", defaults: new { controller = "UserAdmin", action = "Edit" } ); routes.MapRoute( name: null, template: "roles", defaults: new { controller = "RoleAdmin", action = "Index" } ); routes.MapRoute( name: null, template: "roles/new", defaults: new { controller = "RoleAdmin", action = "Create" } ); routes.MapRoute( name: null, template: "roles/remove/{id:required}", defaults: new { controller = "RoleAdmin", action = "RemoveFromRole" } ); routes.MapRoute( name: null, template: "roles/add/{id:required}", defaults: new { controller = "RoleAdmin", action = "AddToRole" } ); routes.MapRoute( name: null, template: "roles/trash/{id:required}", defaults: new { controller = "RoleAdmin", action = "Delete" } ); routes.MapRoute( name: null, template: "denied", defaults: new { controller = "Account", action = "AccessDenied" } ); routes.MapRoute( name: null, template: "categories", defaults: new { controller = "CategoryAdmin", action = "Index" } ); routes.MapRoute( name: null, template: "categories/new", defaults: new { controller = "CategoryAdmin", action = "Create" } ); routes.MapRoute( name: null, template: "categories/trash/{id:int}", defaults: new { controller = "CategoryAdmin", action = "Delete" } ); routes.MapRoute( name: null, template: "categories/change/{id:int}", defaults: new { controller = "CategoryAdmin", action = "Edit" } ); routes.MapRoute( name: null, template: "admins/blogs/{page:int}", defaults: new { controller = "BlogAdmin", action = "Index", page = 1 } ); routes.MapRoute( name: null, template: "admins/delete/{id:int}", defaults: new { controller = "BlogAdmin", action = "Delete" } ); routes.MapRoute( name: null, template: "admins/new", defaults: new { controller = "BlogAdmin", action = "Add" } ); routes.MapRoute( name: null, template: "blogs/new", defaults: new { controller = "Blog", action = "Create" } ); routes.MapRoute( name: null, template: "blogs/delete/{id:int}", defaults: new { controller = "Blog", action = "Delete" } ); routes.MapRoute( name: null, template: "blogs/change/{id:int}", defaults: new { controller = "Blog", action = "Edit" } ); routes.MapRoute( name: null, template: "", defaults: new { controller = "Blog", action = "Index" } ); }); CurrentHttpContext.Configure(app); SeedDatabase.SeedCategory(app); SeedDatabase.SeedBlog(app); SeedDatabase.SeedIdentity(app); }
private static string GetHostname() { return(CurrentHttpContext.Instance().Request.ServerVariables["SERVER_NAME"]); }
/// <summary> /// 在请求执行完后 记录请求的数据以及返回数据 /// </summary> /// <param name="actionExecutedContext"></param> /// <param name="cancellationToken"></param> /// <returns></returns> public override Task OnActionExecutedAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken) { object beginTime = null; if (actionExecutedContext.Request.Properties.TryGetValue(key, out beginTime)) { var menuAction = actionExecutedContext.ActionContext.ActionDescriptor.GetCustomAttributes <MenuAttribute>().OfType <MenuAttribute>().FirstOrDefault(); var menuAction1 = actionExecutedContext.ActionContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes <MenuAttribute>().OfType <MenuAttribute>().FirstOrDefault(); HttpRequestBase request = CurrentHttpContext.Instance().Request; DateTime time = DateTime.FromBinary(Convert.ToInt64(beginTime)); //var accessChannelInfo = ConfigurationHelper.AccessChannelSetting; // load AccessChannel.xml SysOperationLog apiActionLog = new SysOperationLog(); //提取Identity var id = CurrentHttpContext.Instance().User.Identity as ClaimsIdentity; if (id != null) { int accessChannelId = 0; int.TryParse(id?.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Actor)?.Value, out accessChannelId); var appType = id?.Claims.FirstOrDefault(x => x.Type == ClaimTypes.System)?.Value; var token = id?.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Authentication)?.Value; apiActionLog.SourceEquipment = appType; apiActionLog.Token = token; var data = id?.Claims.FirstOrDefault(x => x.Type == ClaimTypes.UserData)?.Value; if (data != null) { var user = JsonConvert.DeserializeObject <SysUser>(data); if (user != null) { //获取用户token apiActionLog.UserId = user.Id; } } } else { apiActionLog.SourceEquipment = "未知"; //获取用户token apiActionLog.UserId = 0; } //获取action名称 apiActionLog.MethodAction = actionExecutedContext.ActionContext.ActionDescriptor.ActionName; //获取Controller 名称 apiActionLog.FunctionController = actionExecutedContext.ActionContext.ActionDescriptor.ControllerDescriptor.ControllerName; //获取action开始执行的时间 apiActionLog.ExecutionTime = time; //获取执行action的耗时 apiActionLog.ExecutionDuration = (DateTime.Now - time).Milliseconds; apiActionLog.Navigator = request.UserAgent; //获取访问的ip ExploreHelper eh = new ExploreHelper(request); apiActionLog.ClientIpAddress = eh.ClientIP; //客户端名称 apiActionLog.ClientName = eh.ClientMachineName; //Url来源 apiActionLog.UrlReferrer = request.UrlReferrer != null ? request.UrlReferrer.AbsoluteUri : ""; //浏览器信息 apiActionLog.BrowserInfo = request.Browser.Browser + " - " + request.Browser.Version + " - " + request.Browser.Type; //获取request提交的参数 apiActionLog.Parameters = GetRequestValues(actionExecutedContext) + " " + GetRequestActionValues(actionExecutedContext); //获取response响应的结果 //apiActionLog.Exception = GetResponseValues(actionExecutedContext); // "",JsonConvert.SerializeObject(actionExecutedContext.Response.RequestMessage); try { apiActionLog.IPNum = (int)StringHelper.IPToInt(eh.ClientIP); } catch { apiActionLog.IPNum = 0; } apiActionLog.Description = msg; apiActionLog.RequestUri = request.Url.AbsoluteUri; apiActionLog.Enabled = 1; WriteLogService.WriteLogOperate(apiActionLog); } return(base.OnActionExecutedAsync(actionExecutedContext, cancellationToken)); }
/// <summary>Assigns a rewrite path.</summary> /// <param name="path">The path to the template that will handle the request.</param> public void RewritePath(string path) { CurrentHttpContext.RewritePath(path, false); }