• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# ActionExecutingContext类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中ActionExecutingContext的典型用法代码示例。如果您正苦于以下问题:C# ActionExecutingContext类的具体用法?C# ActionExecutingContext怎么用?C# ActionExecutingContext使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



ActionExecutingContext类属于命名空间,在下文中一共展示了ActionExecutingContext类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: OnActionExecuting

 public override void OnActionExecuting(ActionExecutingContext context)
 {
     if (!context.RouteData.DataTokens.ContainsKey("actionName"))
     {
         context.RouteData.DataTokens.Add("actionName", context.ActionDescriptor.Name);
     }
 }
开发者ID:huoxudong125,项目名称:Mvc,代码行数:7,代码来源:RoutingController.cs


示例2: OnActionExecuting

        public override void OnActionExecuting(ActionExecutingContext actionContext)
        {
            var clientKeyString = actionContext.HttpContext.Request.Headers["ClientKey"];

            if (string.IsNullOrWhiteSpace(clientKeyString))
            {
                var objectResult = new ObjectResult(ErrorDto.Create("ClientKey is not provided", DocumentationLinks.ClientKey));
                objectResult.StatusCode = StatusCodes.Status403Forbidden;
                actionContext.Result = objectResult;
                return;
            }

            Guid clientKey = Guid.Empty;
            if(!Guid.TryParse(clientKeyString, out clientKey))
            {
                var objectResult = new ObjectResult(ErrorDto.Create("ClientKey have bad format", DocumentationLinks.ClientKey));
                objectResult.StatusCode = StatusCodes.Status403Forbidden;
                actionContext.Result = objectResult;
                return;
            }

            if(!_externalClientService.IsClientKeyValid(clientKey))
            {
                var objectResult = new ObjectResult(ErrorDto.Create("ClientKey is not authorized", DocumentationLinks.ClientKey));
                objectResult.StatusCode = StatusCodes.Status403Forbidden;
                actionContext.Result = objectResult;
            }
        }
开发者ID:mczachurski,项目名称:manager-backend,代码行数:28,代码来源:CheckClientKeyAttribute.cs


示例3: OnActionExecuting

        public override void OnActionExecuting(ActionExecutingContext context)
        {
            if (context.RouteData.Values[routeField] == null)
                claimValue = null;
            else
                claimValue = context.RouteData.Values[routeField].ToString();

            var user = context.HttpContext.User;
            foreach (var r in roles)
            {
                if (user.IsInRole(r))
                {
                    base.OnActionExecuting(context);
                    return;
                }
            }
            if (!string.IsNullOrEmpty(claimValue))
            {
                foreach(var c in claimTypes)
                {
                    if (user.HasClaim(c, claimValue))
                    {
                        base.OnActionExecuting(context);
                        return;
                    }
                }
            }
            HandleUnauthorizedRequest(context);
        }
开发者ID:CodeComb,项目名称:Extensions,代码行数:29,代码来源:AnyRolesOrClaimsAttribute.cs


示例4: OnActionExecuting

 public override void OnActionExecuting(ActionExecutingContext context)
 {
     if (context.HttpContext.User.Identity.IsAuthenticated)
         HandleUnauthorizedRequest(context);
     else
         base.OnActionExecuting(context);
 }
开发者ID:CodeComb,项目名称:Extensions,代码行数:7,代码来源:GuestOnlyAttribute.cs


示例5: OnActionExecuting

        public override void OnActionExecuting(ActionExecutingContext context)
        {
            var gitHubAccessToken = context.HttpContext.Session.GetString("GitHubAccessToken");
            var gitHubName = context.HttpContext.Session.GetString("GitHubName");

            // If session state didn't have our data, either there's no one logged in, or they just logged in
            // but the claims haven't yet been read.
            if (string.IsNullOrEmpty(gitHubAccessToken))
            {
                if (!context.HttpContext.User.Identity.IsAuthenticated)
                {
                    // Not authenticated at all? Go to GitHub to authorize the app
                    context.Result = new ChallengeResult(
                        authenticationScheme: "GitHub",
                        properties: new AuthenticationProperties { RedirectUri = "/" });
                    return;
                }

                // Authenticated but haven't read the claims? Process the claims
                gitHubAccessToken = context.HttpContext.User.FindFirst("access_token")?.Value;
                gitHubName = context.HttpContext.User.Identity.Name;
                context.HttpContext.Session.SetString("GitHubAccessToken", gitHubAccessToken);
                context.HttpContext.Session.SetString("GitHubName", gitHubName);
            }

            context.ActionArguments.Add("gitHubAccessToken", gitHubAccessToken);
            context.ActionArguments.Add("gitHubName", gitHubName);
        }
开发者ID:cjqian,项目名称:ProjectKIssueList,代码行数:28,代码来源:GitHubAuthDataAttribute.cs


示例6: GetAntiXsrfToken

        //parts that contains this. 
        /*
        1. This action filter attribute
        ---------------------------------------------------
        2. CourseAdd - View = 
            @inject Microsoft.AspNet.Antiforgery.IAntiforgery Xsrf
            @functions
            {
                public string GetAntiXsrfToken()
                    {
                        var tokens = Xsrf.GetTokens(Context);
                        return tokens.CookieToken + ":" + tokens.FormToken;
                    }
                }

            <form....>
             <input type="hidden" name="__RequestVerificationToken" value="@GetAntiXsrfToken()" />

           ---------------------------------------------------
            3. Angular controller
              var token = $('[name=__RequestVerificationToken]').val();

                var config = {
                    headers: {
                        'RequestVerificationToken': token
                    }
                };

                //$scope.model 

                $http.post('AddACourse', $scope.model, config)
                   .then(function (response) {
                       debugger;
                       var s = response;

                       $scope.model.Location = 'teststest';

                       // this callback will be called asynchronously
                       // when the response is available
                   }, function (response) {
                       var s = response;
                       // called asynchronously if an error occurs
                       // or server returns response with an error status.
                   });

            4. Mvc Controller
              [ValidateCustomAntiForgeryToken()]
    */

        public override void OnActionExecuting(ActionExecutingContext actionContext)
        {
            IAntiforgery antiforgery = actionContext.HttpContext.ApplicationServices.GetService(typeof(IAntiforgery)) as IAntiforgery;

            var cookieToken = string.Empty;
            var formToken = string.Empty;
            StringValues tokenHeaders;
            string[] tokens = null;

            //go grab this token
            if (actionContext.HttpContext.Request.Headers.TryGetValue("RequestVerificationToken", out tokenHeaders))
            {
                tokens = tokenHeaders.First().Split(':');

                if (tokens != null && tokens.Length == 2)
                {
                    cookieToken = tokens[0];
                    formToken = tokens[1];
                }
                else
                {
                    throw new Exception("Can't Find Request Verification Token");
                }
            }
            else
            {
                throw new Exception("Can't Find Request Verification Token");
            }


            antiforgery.ValidateTokens(actionContext.HttpContext, new AntiforgeryTokenSet(formToken, cookieToken));

            base.OnActionExecuting(actionContext);
        }
开发者ID:dibiancoj,项目名称:ToracGolf,代码行数:83,代码来源:ValidateCustomAntiForgeryTokenAttribute.cs


示例7: HandleAuthorization

        public bool HandleAuthorization(ActionExecutingContext context)
        {
            Console.WriteLine("[RecAaaService] Handling Authorization");
            var controllerName = context.RouteData.Values["Controller"]?.ToString();
            var errorType = string.Empty;

            if (controllerName == null)
                errorType = "Invalid Route";
            else if (!FunctionList.Keys.Contains(controllerName))
                errorType = "Invalid Controller";
            else
            {
                //var roleService = AutoSessionServiceFactory.GetRoleService(ServiceDbConnStr);
                //var permissions = roleService.GetPermissionsByCurrentUserID();
                //if (!permissions.Contains(FunctionList[controllerName]))
                //    errorType = "No-Access-Right";
                var sessonUserIdStr = context.HttpContext.Session.GetString("UI.CURRENT_USERID");
                var sessonUserId = int.Parse(sessonUserIdStr);
                var permissions = GetUserPermission(sessonUserId);
                //or even just if(permissions.IndexOf(FunctionList[controllerName]) < 0)
                if (Array.IndexOf(permissions.Split(','), FunctionList[controllerName]) < 0)
                    errorType = "No-Access-Right";
            }

            if (errorType.Equals(string.Empty)) return true; //No error

            if (!IsAjaxRequest(context.HttpContext.Request))
                context.Result = new RedirectResult(RedirectToWomUrl);
            else
                context.Result = new JsonResult(new { Data = new { isSuccess = false, errorType } });

            return false;
        }
开发者ID:ferrywlto,项目名称:PhotoManWebApi,代码行数:33,代码来源:RecAAAService.cs


示例8: OnActionExecuting

 public override void OnActionExecuting(ActionExecutingContext context)
 {
     if (!context.ModelState.IsValid)
     {
         context.Result = new BadRequestObjectResult(context.ModelState);
     }
 }
开发者ID:huoxudong125,项目名称:Mvc,代码行数:7,代码来源:ModelStateValidationFilterAttribute.cs


示例9: OnActionExecuting

        public override void OnActionExecuting(ActionExecutingContext context)
        {
            var uowParam = context.ActionDescriptor.Parameters.FirstOrDefault(x => x.ParameterType == typeof(IUnitOfWork));
            if (uowParam != null)
            {
                var connectionKey = this.GetType().GetCustomAttribute<ConnectionKeyAttribute>();
                if (connectionKey == null)
                    throw new ArgumentNullException("connectionKey");

                this.connection = SqlConnections.NewByKey(connectionKey.Value);
                this.unitOfWork = new UnitOfWork(connection);
                context.ActionArguments[uowParam.Name] = this.unitOfWork;
                base.OnActionExecuting(context);
                return;
            }

            var cnnParam = context.ActionDescriptor.Parameters.FirstOrDefault(x => x.ParameterType == typeof(IDbConnection));
            if (cnnParam != null)
            {
                var connectionKey = this.GetType().GetCustomAttribute<ConnectionKeyAttribute>();
                if (connectionKey == null)
                    throw new ArgumentNullException("connectionKey");

                this.connection = SqlConnections.NewByKey(connectionKey.Value);
                context.ActionArguments[cnnParam.Name] = connection;
                base.OnActionExecuting(context);
            }

            base.OnActionExecuting(context);
        }
开发者ID:volkanceylan,项目名称:Serenity,代码行数:30,代码来源:ServiceEndpoint.cs


示例10: OnActionExecuting

        public override void OnActionExecuting(ActionExecutingContext context)
        {
            if (!context.HttpContext.User.Identity.IsAuthenticated)
            {
                context.Result = new HttpStatusCodeResult((int)System.Net.HttpStatusCode.Forbidden);
            }
            else
            {
                var scopeAttribute = (ScopeAttribute)context.Controller.GetType().GetTypeInfo().GetCustomAttribute(typeof(ScopeAttribute));

                var result = from claim in context.HttpContext.User.Claims
                    where claim.Type == "scope"
                    select claim;
                if (!result.Any())
                {
                    context.Result = new HttpStatusCodeResult((int) System.Net.HttpStatusCode.Forbidden);
                    return;
                }
                var scopeClaim = result.First();
                if (!scopeAttribute.Values.Contains(scopeClaim.Value))
                {
                    context.Result = new HttpStatusCodeResult((int)System.Net.HttpStatusCode.Forbidden);
                    return;
                }
            }

            base.OnActionExecuting(context);
        }
开发者ID:ghstahl,项目名称:vNext.Jan2016Web,代码行数:28,代码来源:AuthApiActionFilter.cs


示例11: OnActionExecutionAsync

 public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
 {
     if (context.HttpContext.Request.Method == "GET")
     {
         await HandleQueryRequest(context, next);
     }
 }
开发者ID:reeseoo,项目名称:OpenBookAPI,代码行数:7,代码来源:HttpCacheActionFilter.cs


示例12: OnActionExecuting

        public override void OnActionExecuting(ActionExecutingContext context)
        {
            if (!context.ModelState.IsValid)
            {
                var bodyParameter = context.ActionDescriptor
                                          .Parameters
                                          .FirstOrDefault(parameter => IsBodyBindingSource(
                                              parameter.BindingInfo?.BindingSource));
                if (bodyParameter != null)
                {
                    // Body model binder normally reports errors for parameters using the empty name.
                    var parameterBindingErrors = context.ModelState[bodyParameter.Name]?.Errors ??
                        context.ModelState[string.Empty]?.Errors;
                    if (parameterBindingErrors != null && parameterBindingErrors.Count != 0)
                    {
                        var errorInfo = new ErrorInfo
                        {
                            ActionName = context.ActionDescriptor.Name,
                            ParameterName = bodyParameter.Name,
                            Errors = parameterBindingErrors.Select(x => x.ErrorMessage).ToList(),
                            Source = "filter"
                        };

                        context.Result = new ObjectResult(errorInfo);
                    }
                }
            }

            base.OnActionExecuting(context);
        }
开发者ID:huoxudong125,项目名称:Mvc,代码行数:30,代码来源:ValidateBodyParameterAttribute.cs


示例13: OnActionExecuting

 public override void OnActionExecuting(ActionExecutingContext context)
 {
     if (context.HttpContext.Session.GetString("Admin") != "true")
         context.Result = new RedirectResult("/Admin/Login");
     else
         base.OnActionExecuting(context);
 }
开发者ID:Kagamine,项目名称:YuukoBlog.vNext,代码行数:7,代码来源:AdminRequiredAttribute.cs


示例14: OnActionExecuting

        public void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var messages = Convert.ToString(_httpContextAccessor.HttpContext.Request.Cookies[CookiePrefix]);
            if (String.IsNullOrEmpty(messages))
            {
                return;
            }

            IList<NotifyEntry> messageEntries;

            messageEntries = DeserializeNotifyEntries(messages);
            if(messageEntries == null)
            {
                // An error occured during deserialization
                _shouldDeleteCookie = true;
                return;
            }

            if (!messageEntries.Any())
            {
                return;
            }

            // Make the notifications available for the rest of the current request.
            _existingEntries = messageEntries;
        }
开发者ID:MichaelPetrinolis,项目名称:Orchard2,代码行数:26,代码来源:NotifyFilter.cs


示例15: OnActionExecuting

 public override void OnActionExecuting(ActionExecutingContext context)
 {
     userAgent = Request?.UserAgent();
     IsMobile = Request != null ? Request.IsMobileBrowser() : false;
     ViewData["IsMobile"] = IsMobile;
     base.OnActionExecuting(context);
 }
开发者ID:asimshah,项目名称:apollo-web,代码行数:7,代码来源:BaseController.cs


示例16: OnActionExecuting

        public override void OnActionExecuting(ActionExecutingContext context)
        {
            object age = null;

            var controller = context.Controller as FiltersController;

            if (controller != null)
            {
                controller.CustomUser.Log += "Age Enhanced!" + Environment.NewLine;
            }

            if (context.ActionArguments.TryGetValue("age", out age))
            {
                if (age is int)
                {
                    var intAge = (int)age;

                    if (intAge < 21)
                    {
                        intAge += 5;
                    }
                    else if (intAge > 30)
                    {
                        intAge = 29;
                    }

                    context.ActionArguments["age"] = intAge;
                }
            }
        }
开发者ID:huoxudong125,项目名称:Mvc,代码行数:30,代码来源:AgeEnhancerFilterAttribute.cs


示例17: OnActionExecuting

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var httpsPort = Convert.ToInt32(ConfigurationManager.AppSettings["httpsPort"]);
            var httpPort = Convert.ToInt32(ConfigurationManager.AppSettings["httpPort"]);
            var request = filterContext.HttpContext.Request;
            var response = filterContext.HttpContext.Response;

            if (httpsPort > 0 && RequireSecure)
            {
                string url = null;
                if (httpsPort > 0)
                {
                    url = "https://" + request.Url.Host + request.RawUrl;

                    if (httpsPort != 443)
                    {
                        var builder = new UriBuilder(url) { Port = httpsPort };
                        url = builder.Uri.ToString();
                    }
                }
                if (httpsPort != request.Url.Port)
                {
                    filterContext.Result = new RedirectResult(url);
                }
            }
            // se for uma conexao segura e não está requerendo um SSL, retira o ssl e volta para http.
            else if (filterContext.HttpContext.Request.IsSecureConnection && !RequireSecure)
            {
                filterContext.Result = new RedirectResult(filterContext.HttpContext.Request.Url.ToString().Replace("https:", "http:").Replace(httpsPort.ToString(), httpPort.ToString()));
                filterContext.Result.ExecuteResult(filterContext);
            }
            base.OnActionExecuting(filterContext);
    }
开发者ID:rodrigoporcionato,项目名称:CodeStaff,代码行数:33,代码来源:RequireHttpsAttribute.cs


示例18: OnActionExecuting

 public override void OnActionExecuting(ActionExecutingContext context)
 {
     if (!string.IsNullOrEmpty(context.HttpContext.Request.Query["culture"]))
     {
         CultureInfo.DefaultThreadCurrentCulture = CultureInfo.DefaultThreadCurrentUICulture = new CultureInfo(context.HttpContext.Request.Query["culture"]);
     }
     base.OnActionExecuting(context);
 }
开发者ID:al-main,项目名称:ui-for-aspnet-mvc-6-demos,代码行数:8,代码来源:GlobalizationController.cs


示例19: OnActionExecuting

 public override void OnActionExecuting(ActionExecutingContext context)
 {
     if (context.ActionDescriptor.DisplayName == "FiltersWebSite.ActionFilterController.GetHelloWorld")
     {
         (context.ActionArguments["fromGlobalActionFilter"] as List<ContentResult>).
             Add(Helpers.GetContentResult(context.Result, "Action Filter - OnActionExecuting"));
     }
 }
开发者ID:huoxudong125,项目名称:Mvc,代码行数:8,代码来源:ChangeContentActionFilter.cs


示例20: OnActionExecuting

 public override void OnActionExecuting(ActionExecutingContext context)
 {
     if (context.ModelState.IsValid == false)
     {
         context.Result = new BadRequestObjectResult(context.ModelState.Values
             .SelectMany(p=>p.Errors).First(p=>p.ErrorMessage!="" || p.Exception!=null).ErrorMessage);
     }
 }
开发者ID:yaoyel,项目名称:Finework,代码行数:8,代码来源:ValidateModelStateAttribute.cs



注:本文中的ActionExecutingContext类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# ActionGetter类代码示例发布时间:2022-05-24
下一篇:
C# ActionExecutedContext类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap