当前位置: 首页>>代码示例>>C#>>正文


C# ActionExecutingContext类代码示例

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


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


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