//Test probíhá před spuštěním každé Akce! public override void OnActionExecuting(Microsoft.AspNetCore.Mvc.Filters.ActionExecutingContext context) { //předání přihlášeného uživatele do Factory BO.RunningUser ru = (BO.RunningUser)HttpContext.RequestServices.GetService(typeof(BO.RunningUser)); if (string.IsNullOrEmpty(ru.j03Login)) { ru.j03Login = context.HttpContext.User.Identity.Name; } if (this.Factory == null) { this.Factory = (BL.Factory)HttpContext.RequestServices.GetService(typeof(BL.Factory)); } if (Factory.CurrentUser == null || Factory.CurrentUser.isclosed) { context.Result = new RedirectResult("~/Login/UserLogin"); return; } if (Factory.CurrentUser.j03IsMustChangePassword && context.RouteData.Values["action"].ToString() != "ChangePassword") { context.Result = new RedirectResult("~/Home/ChangePassword"); // RedirectToAction("ChangePassword", "Home"); } //Příklad přesměrování stránky jinam: //context.Result = new RedirectResult("~/Home/Index"); }
public override void OnActionExecuting(ActionExecutingContext context) { if (context.RouteData.Values["id"] != null && context.RouteData.Values["userId"] == null) { //id = userId var result = _db.DocumentRepository.GetMany(p => p.UserId == context.RouteData.Values["id"].ToString() && (p.Approve == 1), null, ""); if (result.Any()) { base.OnActionExecuting(context); } else { context.Result = new ForbidResult(); } } else { //userId = userId var result = _db.DocumentRepository.GetMany(p => p.UserId == context.RouteData.Values["userId"].ToString() && (p.Approve == 1), null, ""); if (result.Any()) { base.OnActionExecuting(context); } else { context.Result = new ForbidResult(); } } }
public override void OnActionExecuting(Microsoft.AspNetCore.Mvc.Filters.ActionExecutingContext context) { ViewData["userId"] = null; if (User.Identity.IsAuthenticated) { ViewData["userId"] = User.FindFirst(ClaimTypes.NameIdentifier).Value; } }
public override void OnActionExecuting(Microsoft.AspNetCore.Mvc.Filters.ActionExecutingContext context) { // т.к. содержимое ViewBag не сохраняется при последовательных обращениях, то значения необходимо восстанавливать. // на момент работы конструктора HttpContext еще не устновлен, поэтому заполнять ViewBag в нем бесполезно, // делаем это перед обращением к Action ViewBag.FileSizeMax = m_fileSizeMax; ViewBag.FileSizeMaxText = ByteSize.FromBytes(m_fileSizeMax).ToString(); ViewBag.AllowedFileTypes = m_allowedFileTypes; ViewBag.AllowedFileTypesText = string.Join(", ", m_allowedFileTypes.Select(ft => $"<strong>{ft}</strong>")); ViewBag.FileTypesAcceptValue = string.Join(",", m_allowedFileTypes.Select(ft => $".{ft}")); }
/* * Model state is applied only to POST methods. * it can be applied for GET methods but it will fail when the call has nullable parameters * ex: http://localhost:5000/api/Session/ListCashierSessions/1/null/null/[email protected]/null */ public override void OnActionExecuting(Microsoft.AspNetCore.Mvc.Filters.ActionExecutingContext context) { if (context.HttpContext.Request.Method != "GET" && !context.ModelState.IsValid) { context.Result = new BadRequestObjectResult(context.ModelState); var errorString = string.Join("; ", context.ModelState.Values.ToList() .SelectMany(v => v.Errors) .Select(x => x.ErrorMessage)); _logger.LogError($"Bad Request: {errorString}"); } }
public override Task OnActionExecutionAsync(Microsoft.AspNetCore.Mvc.Filters.ActionExecutingContext context, Microsoft.AspNetCore.Mvc.Filters.ActionExecutionDelegate next) { var prevUrl = Request.Headers["Referer"].ToString(); if (prevUrl == "") { prevUrl = Url.Action("Index", "Home"); } ViewBag.PreviousUrl = prevUrl; return(base.OnActionExecutionAsync(context, next)); }
public override Task OnActionExecutionAsync(Microsoft.AspNetCore.Mvc.Filters.ActionExecutingContext context, Microsoft.AspNetCore.Mvc.Filters.ActionExecutionDelegate next) { if (!ModelState.IsValid) { context.Result = new BadRequestObjectResult(context.ModelState); } else { return(next()); } return(Task.CompletedTask); }
public override void OnActionExecuting(Microsoft.AspNetCore.Mvc.Filters.ActionExecutingContext context) { if (hasIdentity) { //if (!context.HttpContext.Session.HasUserData()) //{ // context.Result = new RedirectToActionResult("Index", "Error", new { errorType = ErrorType.ErrorNoUserOrTimeOut }); // return; //} } base.OnActionExecuting(context); }
public override void OnActionExecuting(Microsoft.AspNetCore.Mvc.Filters.ActionExecutingContext context) { base.OnActionExecuting(context); HttpContext.Request.Headers.TryGetValue("Authorization", out var apiSecretKey); if (apiSecretKey.Count() > 0) { this.apiSecretKey = apiSecretKey; this.api = _dbContext.Apis.Where(q => q.SecretKey == apiSecretKey).FirstOrDefault(); } }
public override void OnActionExecuting(Microsoft.AspNetCore.Mvc.Filters.ActionExecutingContext context) { base.OnActionExecuting(context); Util.IUserCache userCache = context.HttpContext.RequestServices.GetService(typeof(Util.IUserCache)) as Util.IUserCache; var result = userCache.GetUserInformation(); if (string.IsNullOrEmpty(userCache.GetTokenUser()) || !CheckAndRenewToken().Result) { context.Result = new RedirectToRouteResult(new Microsoft.AspNetCore.Routing.RouteValueDictionary(new { controller = "UserAccount", action = "Login", area = "" })); } }
public override void OnActionExecuting(ActionExecutingContext filterContext) { var req = filterContext.HttpContext.Request; var auth = req.Headers["Authorization"]; if (!String.IsNullOrEmpty(auth)) { var cred = System.Text.ASCIIEncoding.ASCII.GetString(Convert.FromBase64String(auth.ToString().Substring(6))).Split(':'); var user = new { Name = cred[0], Pass = cred[1] }; if (user.Name == Username && user.Pass == Password) { return; } } var res = filterContext.HttpContext.Response; filterContext.HttpContext.Response.Headers.Add("WWW-Authenticate", String.Format("Basic realm=\"{0}\"", BasicRealm ?? "Ryadel")); /// thanks to eismanpat for this line: http://www.ryadel.com/en/http-basic-authentication-asp-net-mvc-using-custom-actionfilter/#comment-2507605761 filterContext.Result = new UnauthorizedResult(); }
public override void OnActionExecuting(Microsoft.AspNetCore.Mvc.Filters.ActionExecutingContext context) { SetContext(context.HttpContext); Logger.LogInformation(string.Format("[{0}] INIT: {1}", DateTime.Now.ToString(), context.ActionDescriptor.DisplayName)); }
/// <summary>动作执行前</summary> /// <param name="context"></param> #if __CORE__ public override void OnActionExecuting(Microsoft.AspNetCore.Mvc.Filters.ActionExecutingContext context)
public override Task OnActionExecutionAsync(Microsoft.AspNetCore.Mvc.Filters.ActionExecutingContext context, Microsoft.AspNetCore.Mvc.Filters.ActionExecutionDelegate next) { try { var userAgent = context.HttpContext.Request.Headers["User-Agent"].ToString(); if (userAgent.Contains("MicroMessenger")) { SourceType = SourceType.WeChatApp; } else if (userAgent.Contains("iPhone") || userAgent.Contains("iPod") || userAgent.Contains("iPad")) { SourceType = SourceType.IOS; } else if (userAgent.Contains("Android")) { SourceType = SourceType.Android; } else { //TODO:the last del SourceType = SourceType.Web; } foreach (var kv in context.HttpContext.Request.Query) { ReqParams[kv.Key] = kv.Value.ToString(); } if (context.HttpContext.Request.HasFormContentType) { foreach (var kv in context.HttpContext.Request.Form) { ReqParams[kv.Key] = kv.Value.ToString(); } } var values = context.HttpContext.GetContextDict(); foreach (var kv in values) { ReqParams[kv.Key] = kv.Value.ToString(); } if (SourceType == SourceType.Unknown) { context.Result = new ObjectResult(new MyResult <object>().SetStatus(ErrorCode.Unauthorized, "请设置User-Agent请求头: 如:iPhone 或者 Android 或则web")); } else { var token = string.Empty; var sign = string.Empty; if (ReqParams.ContainsKey(TOKEN_NAME)) { token = ReqParams[TOKEN_NAME]; } if (ReqParams.ContainsKey(Sign)) { sign = ReqParams[Sign]; } //can get token from server redis now only get form params // .. // if (!context.ActionDescriptor.FilterDescriptors.Any(t => t.Filter is AllowAnonymousFilter))//need check token { if (string.IsNullOrEmpty(token)) { context.Result = new ObjectResult(new MyResult <object>(ErrorCode.Unauthorized, "token is empty you are error!")); } else if (string.IsNullOrEmpty(sign)) { context.Result = new ObjectResult(new MyResult <object>(ErrorCode.Unauthorized, "sign is empty you are error!")); } else { var model = CheckToken(token, sign); if (model.Success) { //ok } if (!model.Success) { context.Result = new ObjectResult(model); } } } else { if (string.IsNullOrEmpty(token)) { TokenModel = new TokenModel(); } else { var json = DataProtectionUtil.UnProtect(token); if (string.IsNullOrEmpty(json)) { TokenModel = new TokenModel(); } else { TokenModel = json.GetModel <TokenModel>(); } } } } } catch (System.Exception ex) { LogUtil <ApiBaseController> .Error(ex, ex.Message); context.Result = new ObjectResult(new MyResult <object>(ErrorCode.SystemError, $"请求失败{ex.Message}")); } return(base.OnActionExecutionAsync(context, next)); }
public ActionExecutingContext(Microsoft.AspNetCore.Mvc.Filters.ActionExecutingContext context) { _context = context; }
public override void OnActionExecuting(Microsoft.AspNetCore.Mvc.Filters.ActionExecutingContext context) { base.OnActionExecuting(context); context.HttpContext.Items[URLHELPER] = this.Url; }