/// <summary> /// Main logic to filter user access and override all ScopePageModel derived behaviour /// </summary> /// <param name="context"></param> public override void OnPageHandlerSelected(PageHandlerSelectedContext context) { //Check user validity & feature allowed to be accessed if (AppGlobal.get_user_validity() == false) { Response.StatusCode = (int)HttpStatusCode.Unauthorized; Response.Redirect("/main/forbidden"); //short circuit & send forbidden page } //var context_temp = context.HttpContext.Request.Query; //string content = JsonConvert.SerializeObject(context_temp, Formatting.Indented, //new JsonSerializerSettings { // ReferenceLoopHandling = ReferenceLoopHandling.Serialize //}); //AppGlobal.console_log("content of context", content); //Created short circuit based on page request query, if f is null rejected if (string.IsNullOrEmpty(context.HttpContext.Request.Query["f"])) { Response.StatusCode = (int)HttpStatusCode.Unauthorized; Response.Redirect("/main/forbidden"); //short circuit & send forbidden page } else { //RFC : //1. add logging here, to save : feature accessed, params passed, etc. //2. add more thorough f filtering (if needed) } }
public void OnPageHandlerSelected(PageHandlerSelectedContext context) { context.RouteData.Values.Add("Name", "test"); context.RouteData.Values.Add("Year", 1999); //throw new System.NotImplementedException(); }
public override void OnPageHandlerSelected(PageHandlerSelectedContext context) { int.TryParse(context.RouteData.Values["teamId"]?.ToString(), out var teamId); TeamId = teamId; base.OnPageHandlerSelected(context); }
/// <summary> /// 将视图写入html文件 /// </summary> private async Task WriteViewToFileAsync(PageHandlerSelectedContext context) { try { var html = await RenderToStringAsync(context); if (string.IsNullOrWhiteSpace(html)) { return; } var relativePath = GetPath(context); if (string.IsNullOrWhiteSpace(relativePath)) { return; } var path = Bing.Utils.Helpers.Common.GetPhysicalPath(relativePath); var directory = System.IO.Path.GetDirectoryName(path); if (string.IsNullOrWhiteSpace(directory)) { return; } if (Directory.Exists(directory) == false) { Directory.CreateDirectory(directory); } System.IO.File.WriteAllText(path, html); } catch (Exception ex) { ex.Log(Log.GetLog().Caption("生成html静态文件失败")); } }
/// <summary> /// 选择页面 /// </summary> public async Task OnPageHandlerSelectionAsync(PageHandlerSelectedContext context) { if (context.ActionDescriptor == null) { return; } await WriteViewToFileAsync(context); }
public void OnPageHandlerSelected(PageHandlerSelectedContext context) { if (context.HandlerMethod?.HttpMethod == "Get" && context.HandlerMethod.MethodInfo.Name == "OnGet") { // code placed here will only execute if the OnGet() method has been selected context.HttpContext.Response.Headers.Add("environment", env.EnvironmentName); } }
public void OnPageHandlerSelected(PageHandlerSelectedContext context) { // Chamado depois que um manipulador de método é selecionado, mas antes de ocorrer o model binding context.RouteData.Values.TryGetValue("globalTemplate", out var globalTemplateValue); if (string.Equals((string)globalTemplateValue, "TriggerValue", StringComparison.Ordinal)) { context.RouteData.Values["globalTemplate"] = "ReplacementValue"; } }
public void OnPageHandlerSelected(PageHandlerSelectedContext context) { var attrs = GetAttrs(context); foreach (var attr in attrs) { attr.OnPageHandlerSelected(context); } }
public void OnPageHandlerSelected(PageHandlerSelectedContext context) { var key = _config["UserAgentID"]; context.HttpContext.Request.Headers.TryGetValue("user-agent", out StringValues value); ProcessUserAgent.Write(context.ActionDescriptor.DisplayName, "SamplePageFilter.OnPageHandlerSelected", value, key.ToString()); }
public void OnPageHandlerSelected(PageHandlerSelectedContext context) { var name = context.HandlerMethod?.Name ?? context.HandlerMethod?.MethodInfo.Name; if (name != null) { _diagnosticContext.Set("RazorPageHandler", name); } }
public Task OnPageHandlerSelectionAsync(PageHandlerSelectedContext context) { var key = _configuration["UserAgentID"]; context.HttpContext.Request.Headers.TryGetValue("user-agent", out StringValues value); // to do filter return(Task.CompletedTask); }
public void OnPageHandlerSelected(PageHandlerSelectedContext context) { // Called after a handler method is selected but before model binding occurs. context.RouteData.Values.TryGetValue("globalTemplate", out var globalTemplateValue); if (string.Equals((string)globalTemplateValue, "TriggerValue", StringComparison.Ordinal)) { context.RouteData.Values["globalTemplate"] = "ReplacementValue"; } }
public void OnPageHandlerSelected(PageHandlerSelectedContext context) { var name = context.HandlerMethod?.Name ?? context.HandlerMethod?.MethodInfo.Name; if (name != null) { _diagnosticContext.Set("RazorPageHandler", name); } LoggingExtensions.EnrichFromFilterContext(_diagnosticContext, context); }
public Task OnPageHandlerSelectionAsync(PageHandlerSelectedContext context) { var key = _config["UserAgentID"]; /* * context.HttpContext.Request.Headers.TryGetValue("user-agent", * out StringValues value); * ProcessUserAgent.Write(context.ActionDescriptor.DisplayName, * "SampleAsyncPageFilter.OnPageHandlerSelectionAsync", * value, key.ToString()); */ return(Task.CompletedTask); }
public async Task OnPageHandlerSelectionAsync( PageHandlerSelectedContext context) { var key = _config.GetValue(typeof(string), "UserAgentID"); context.HttpContext.Request.Headers.TryGetValue("user-agent", out StringValues value); ProcessUserAgent.Write(context.ActionDescriptor.DisplayName, "SampleAsyncPageFilter.OnPageHandlerSelectionAsync", value, key.ToString()); await Task.CompletedTask; }
public void OnPageHandlerSelected(PageHandlerSelectedContext context) { var culture = context.HttpContext.Request.Path.Value.Split('/')[1]; try { _supportedCultures.Contains(new CultureInfo(culture)); } catch (CultureNotFoundException e) { context.HttpContext.Response.Redirect("/ru" + context.HttpContext.Request.Path); } }
public void OnPageHandlerSelected(PageHandlerSelectedContext context) { // demonstrating how Page Filters work var factory = context.HttpContext.RequestServices.GetRequiredService <ILoggerFactory>(); var logger = factory.CreateLogger(context.HandlerInstance.ToString()); var instance = context.HandlerInstance as PageModel; if (instance != null) { logger.LogInformation(instance.PageContext.ActionDescriptor.DisplayName); logger.LogInformation($"{context.HandlerInstance.GetType().ToString()} selected."); } }
public Task OnPageHandlerSelectionAsync(PageHandlerSelectedContext context) { if (HandlerNames.Length == 0) { return(string.Equals(context.HandlerMethod?.HttpMethod, HttpMethod.Post.Method, StringComparison.OrdinalIgnoreCase) ? CheckGoogleReCaptchaHelper.CheckGoogleReCaptchaAsync(context, _invisible, _requiredScore, _actionName) : Task.CompletedTask); } return(HandlerNames.Contains(context.HandlerMethod.Name) ? CheckGoogleReCaptchaHelper.CheckGoogleReCaptchaAsync(context, _invisible, _requiredScore, _actionName) : Task.CompletedTask); }
public void OnPageHandlerSelected() { // Arrange var pageHandlerSelectedContext = new PageHandlerSelectedContext( pageContext: _context, filters: new List <IFilterMetadata>(), handlerInstance: new { }); // Act _filter.OnPageHandlerSelected(pageHandlerSelectedContext); // Assert Assert.True(pageHandlerSelectedContext.ModelState.IsValid); }
public static void AfterOnPageHandlerSelected( this DiagnosticListener diagnosticListener, PageHandlerSelectedContext handlerSelectedContext, IPageFilter filter) { Debug.Assert(diagnosticListener != null); Debug.Assert(handlerSelectedContext != null); Debug.Assert(filter != null); // Inlinable fast-path check if Diagnositcs is enabled if (diagnosticListener.IsEnabled()) { AfterOnPageHandlerSelectedImpl(diagnosticListener, handlerSelectedContext, filter); } }
public Task OnPageHandlerSelectionAsync(PageHandlerSelectedContext context) { var key = _config["UserAgentID"]; context.HttpContext.Request.Headers.TryGetValue("user-agent", out StringValues value); Trace.Write($"Action {context.ActionDescriptor.DisplayName} "); if (context.HandlerMethod.MethodInfo.CustomAttributes.Any(a => a.AttributeType == typeof(HiSecure))) { context.HttpContext.Response.StatusCode = 401; return(Task.CompletedTask); } return(Task.CompletedTask); }
/// <summary> /// 获取Html默认生成路径 /// </summary> protected virtual string GetPath(PageHandlerSelectedContext context) { var htmlPath = context.ActionDescriptor.ModelTypeInfo.GetCustomAttribute <HtmlPathAttribute>(); if (htmlPath != null) { if (htmlPath.Ignore) { return(string.Empty); } if (!string.IsNullOrWhiteSpace(htmlPath.Path)) { return(htmlPath.Path); } } if (context.ActionDescriptor is CompiledPageActionDescriptor pageActionDescriptor) { var paths = pageActionDescriptor.RelativePath.TrimStart('/').Split('/'); var result = new StringBuilder(); for (var i = 0; i < paths.Length; i++) { var path = paths[i]; var name = Bing.Utils.Helpers.Str.SplitWordGroup(path); if (name == "pages" && i == 0) { result.Append("typings/app/"); continue; } if (i == paths.Length - 2) { result.Append($"{name}/html/"); continue; } if (i == paths.Length - 1) { name = Bing.Utils.Helpers.Str.SplitWordGroup(path.RemoveEnd(".cshtml")); result.Append($"{name}.component.html"); break; } result.Append($"{name}/"); } return($"/{result}"); } return(string.Empty); }
public override void OnPageHandlerSelected(PageHandlerSelectedContext filterContext) { string tagName = "[Enrollments][CreateModel][OnPageHandlerSelected]"; ApplicationUser appUser = _userManager.GetUserAsync(HttpContext.User).Result; string pageRedirect = _sessionCookieService.DeterminePageRedirect(appUser.UserName, tagName); if (pageRedirect != null) { filterContext.HttpContext.Response.Redirect(pageRedirect); return; } _logger.LogInformation(tagName + " => Refreshing SessinCookie for '" + appUser.UserName + "'"); _sessionCookieService.RefreshSessionCookie(appUser.UserName); }
public override void OnPageHandlerSelected(PageHandlerSelectedContext filterContext) { ApplicationUser appUser = _userManager.GetUserAsync(HttpContext.User).Result; SessionCookie sessionCookie = _sessionCookieService.RetrieveSessionCookie(appUser.UserName); if (sessionCookie == null) { StringBuilder sb = new StringBuilder("[Enrollments][IndexModel][OnPageHandlerSelected] => SessionCookie for '"); sb.Append(appUser.UserName); sb.Append("' NOT FOUND. Redirecting to Login page."); _logger.LogInformation(sb.ToString()); filterContext.HttpContext.Response.Redirect("/Account/LoginPrep"); return; } if (DateTime.Now > sessionCookie.LastAccessedOn.AddMinutes(30)) { StringBuilder sb = new StringBuilder("[Enrollments][IndexModel][OnPageHandlerSelected] => SessionCookie for '"); sb.Append(appUser.UserName); sb.Append("' HAS EXPIRED. It was last accessed on "); sb.Append(sessionCookie.LastAccessedOn); if (DateTime.Now > sessionCookie.LastAccessedOn.AddHours(2)) { sb.Append(". Redirecting to Login page."); _logger.LogInformation(sb.ToString()); filterContext.HttpContext.Response.Redirect("/Account/LoginPrep"); return; } else { sb.Append(". Redirecting to SessionTimeout page."); _logger.LogInformation(sb.ToString()); filterContext.HttpContext.Response.Redirect("/Account/SessionTimeout"); return; } } _logger.LogInformation("[Enrollments][IndexModel][OnPageHandlerSelected] => Refreshing SessinCookie for '" + appUser.UserName + "'"); _sessionCookieService.RefreshSessionCookie(appUser.UserName); }
public Task OnPageHandlerSelectionAsync(PageHandlerSelectedContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (context.HandlerInstance is IAsyncPageFilter asyncPageFilter) { return(asyncPageFilter.OnPageHandlerSelectionAsync(context)); } else if (context.HandlerInstance is IPageFilter pageFilter) { pageFilter.OnPageHandlerSelected(context); } return(Task.CompletedTask); }
public void OnPageHandlerSelected(PageHandlerSelectedContext context) { if (!(context.HandlerInstance is PageModel page)) { return; } var serializedModelState = page.TempData[Key] as string; if (serializedModelState.IsNullOrEmpty()) { return; } var modelState = ModelStateSerializer.Deserialize(serializedModelState); page.ModelState.Merge(modelState); }
public async Task OnPageHandlerSelectionAsync(PageHandlerSelectedContext context) { var attribute = context.HandlerMethod?.MethodInfo?.GetCustomAttribute <AuthorizePageHandlerAttribute>(); if (attribute is null) { return; } var policy = await AuthorizationPolicy.CombineAsync(policyProvider, new[] { attribute }); if (policy is null) { return; } await AuthorizeAsync(context, policy); }
public async Task OnPageHandlerSelectionAsync(PageHandlerSelectedContext context) { if (context.ActionDescriptor.ModelTypeInfo != typeof(Pages.IndexModel)) { throw new NotSupportedException("This only works for IndexModel."); } if (context.HandlerMethod.MethodInfo != typeof(Pages.IndexModel).GetMethod(nameof(Pages.IndexModel.OnPostAuthorized))) { return; } var policy = await policyProvider.GetPolicyAsync("YourAuthPolicyHere"); // Or you may use the default policy if you don't have a specific policy configured. // var policy = policyProvider.GetDefaultPolicyAsync(); await AuthoorizeAsync(context, policy); }
/// <summary> /// 渲染视图 /// </summary> protected async Task <string> RenderToStringAsync(PageHandlerSelectedContext context) { var relativePath = ""; dynamic pageModel = System.Convert.ChangeType(context.HandlerInstance, context.HandlerInstance.GetType()); if (context.ActionDescriptor is CompiledPageActionDescriptor pageActionDescriptor) { relativePath = pageActionDescriptor.RelativePath; } if (relativePath == "/Pages/Index.cshtml") { return(string.Empty); } if (pageModel == null) { throw new ArgumentException(nameof(pageModel)); } var razorViewEngine = Ioc.Create <IRazorViewEngine>(); var activator = Ioc.Create <IRazorPageActivator>(); var actionContext = new ActionContext(context.HttpContext, pageModel.RouteData, context.ActionDescriptor); var razorPage = FindPage(razorViewEngine, actionContext, relativePath); using (var stringWriter = new StringWriter()) { var view = new RazorView(razorViewEngine, activator, new List <IRazorPage>(), razorPage, HtmlEncoder.Default, new DiagnosticListener("ViewRenderService")); var viewContext = new ViewContext(actionContext, view, pageModel?.ViewData, pageModel?.TempData, stringWriter, new HtmlHelperOptions()) { ExecutingFilePath = relativePath }; var pageNormal = ((Page)razorPage); pageNormal.PageContext = pageModel.PageContext; pageNormal.ViewContext = viewContext; activator.Activate(pageNormal, viewContext); await razorPage.ExecuteAsync(); return(stringWriter.ToString()); } }
public static void AfterOnPageHandlerSelected( this DiagnosticSource diagnosticSource, PageHandlerSelectedContext handlerSelectedContext, IPageFilter filter) { Debug.Assert(diagnosticSource != null); Debug.Assert(handlerSelectedContext != null); Debug.Assert(filter != null); if (diagnosticSource.IsEnabled("Microsoft.AspNetCore.Mvc.AfterOnPageHandlerSelected")) { diagnosticSource.Write( "Microsoft.AspNetCore.Mvc.AfterOnPageHandlerSelected", new { actionDescriptor = handlerSelectedContext.ActionDescriptor, handlerSelectedContext = handlerSelectedContext, filter = filter }); } }