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


C# ActionContext类代码示例

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


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

示例1: AddValidation_DoesNotTrounceExistingAttributes

        public void AddValidation_DoesNotTrounceExistingAttributes()
        {
            // Arrange
            var provider = TestModelMetadataProvider.CreateDefaultProvider();
            var metadata = provider.GetMetadataForProperty(typeof(string), "Length");

            var attribute = new RangeAttribute(typeof(decimal), "0", "100");
            attribute.ErrorMessage = "The field Length must be between {1} and {2}.";

            var adapter = new RangeAttributeAdapter(attribute, stringLocalizer: null);

            var actionContext = new ActionContext();
            var context = new ClientModelValidationContext(actionContext, metadata, provider, new AttributeDictionary());

            context.Attributes.Add("data-val", "original");
            context.Attributes.Add("data-val-range", "original");
            context.Attributes.Add("data-val-range-max", "original");
            context.Attributes.Add("data-val-range-min", "original");

            // Act
            adapter.AddValidation(context);

            // Assert
            Assert.Collection(
                context.Attributes,
                kvp => { Assert.Equal("data-val", kvp.Key); Assert.Equal("original", kvp.Value); },
                kvp => { Assert.Equal("data-val-range", kvp.Key); Assert.Equal("original", kvp.Value); },
                kvp => { Assert.Equal("data-val-range-max", kvp.Key); Assert.Equal("original", kvp.Value); },
                kvp => { Assert.Equal("data-val-range-min", kvp.Key); Assert.Equal("original", kvp.Value); });
        }
开发者ID:ymd1223,项目名称:Mvc,代码行数:30,代码来源:RangeAttributeAdapterTest.cs

示例2: AddValidation_AddsValidation_Localize

        public void AddValidation_AddsValidation_Localize()
        {
            // Arrange
            var provider = TestModelMetadataProvider.CreateDefaultProvider();
            var metadata = provider.GetMetadataForProperty(typeof(string), "Length");

            var attribute = new RequiredAttribute();

            var expectedProperties = new object[] { "Length" };
            var message = "This paramter is required.";
            var expectedMessage = "FR This parameter is required.";
            attribute.ErrorMessage = message;

            var stringLocalizer = new Mock<IStringLocalizer>();
            stringLocalizer.Setup(s => s[attribute.ErrorMessage, expectedProperties])
                .Returns(new LocalizedString(attribute.ErrorMessage, expectedMessage));

            var adapter = new RequiredAttributeAdapter(attribute, stringLocalizer: stringLocalizer.Object);

            var actionContext = new ActionContext();
            var context = new ClientModelValidationContext(actionContext, metadata, provider, new AttributeDictionary());

            // Act
            adapter.AddValidation(context);

            // Assert
            Assert.Collection(
                context.Attributes,
                kvp => { Assert.Equal("data-val", kvp.Key); Assert.Equal("true", kvp.Value); },
                kvp => { Assert.Equal("data-val-required", kvp.Key); Assert.Equal(expectedMessage, kvp.Value); });
        }
开发者ID:cemalshukriev,项目名称:Mvc,代码行数:31,代码来源:RequiredAttributeAdapterTest.cs

示例3: ClientRulesWithMinLengthAttribute_Localize

        public void ClientRulesWithMinLengthAttribute_Localize()
        {
            // Arrange
            var provider = TestModelMetadataProvider.CreateDefaultProvider();
            var metadata = provider.GetMetadataForProperty(typeof(string), "Length");

            var attribute = new MinLengthAttribute(6);
            attribute.ErrorMessage = "Property must be at least '{1}' characters long.";

            var expectedProperties = new object[] { "Length", 6 };
            var expectedMessage = "Property must be at least '6' characters long.";

            var stringLocalizer = new Mock<IStringLocalizer>();
            stringLocalizer.Setup(s => s[attribute.ErrorMessage, expectedProperties])
                .Returns(new LocalizedString(attribute.ErrorMessage, expectedMessage));

            var adapter = new MinLengthAttributeAdapter(attribute, stringLocalizer: stringLocalizer.Object);

            var actionContext = new ActionContext();
            var context = new ClientModelValidationContext(actionContext, metadata, provider);

            // Act
            var rules = adapter.GetClientValidationRules(context);

            // Assert
            var rule = Assert.Single(rules);
            Assert.Equal("minlength", rule.ValidationType);
            Assert.Equal(1, rule.ValidationParameters.Count);
            Assert.Equal(6, rule.ValidationParameters["min"]);
            Assert.Equal(attribute.FormatErrorMessage("Length"), rule.ErrorMessage);
        }
开发者ID:phinq19,项目名称:git_example,代码行数:31,代码来源:MinLengthAttributeAdapterTest.cs

示例4: Create_TypeActivatesTypesWithServices

        public void Create_TypeActivatesTypesWithServices()
        {
            // Arrange
            var activator = new DefaultControllerActivator(new DefaultTypeActivatorCache());
            var serviceProvider = new Mock<IServiceProvider>(MockBehavior.Strict);
            var testService = new TestService();
            serviceProvider.Setup(s => s.GetService(typeof(TestService)))
                           .Returns(testService)
                           .Verifiable();
                           
            var httpContext = new DefaultHttpContext
            {
                RequestServices = serviceProvider.Object
            };
            var actionContext = new ActionContext(httpContext,
                                                  new RouteData(),
                                                  new ActionDescriptor());
            // Act
            var instance = activator.Create(actionContext, typeof(TypeDerivingFromControllerWithServices));

            // Assert
            var controller = Assert.IsType<TypeDerivingFromControllerWithServices>(instance);
            Assert.Same(testService, controller.TestService);
            serviceProvider.Verify();
        }
开发者ID:huoxudong125,项目名称:Mvc,代码行数:25,代码来源:DefaultControllerActivatorTest.cs

示例5: Activate_PopulatesServicesFromServiceContainer

        public void Activate_PopulatesServicesFromServiceContainer()
        {
            // Arrange
            var urlHelper = Mock.Of<IUrlHelper>();
            var service = new Mock<IServiceProvider>();
            service.Setup(s => s.GetService(typeof(IUrlHelper)))
                   .Returns(urlHelper);

            var httpContext = new Mock<HttpContext>();
            httpContext.SetupGet(c => c.RequestServices)
                       .Returns(service.Object);
            var routeContext = new RouteContext(httpContext.Object);
            var controller = new TestController();
            var context = new ActionContext(routeContext, new ActionDescriptor())
            {
                Controller = controller
            };
            var activator = new DefaultControllerActivator();

            // Act
            activator.Activate(controller, context);

            // Assert
            Assert.Same(urlHelper, controller.Helper);
        }
开发者ID:Nakro,项目名称:Mvc,代码行数:25,代码来源:DefaultControllerActivatorTest.cs

示例6: GetClientValidationRules_WithMaxLength_ReturnsValidationParameters_Localize

        public void GetClientValidationRules_WithMaxLength_ReturnsValidationParameters_Localize()
        {
            // Arrange
            var provider = TestModelMetadataProvider.CreateDefaultProvider();
            var metadata = provider.GetMetadataForProperty(typeof(string), "Length");

            var attribute = new StringLengthAttribute(8);
            attribute.ErrorMessage = "Property must not be longer than '{1}' characters.";

            var expectedMessage = "Property must not be longer than '8' characters.";

            var stringLocalizer = new Mock<IStringLocalizer>();
            var expectedProperties = new object[] { "Length", 0, 8 };

            stringLocalizer.Setup(s => s[attribute.ErrorMessage, expectedProperties])
                .Returns(new LocalizedString(attribute.ErrorMessage, expectedMessage));

            var adapter = new StringLengthAttributeAdapter(attribute, stringLocalizer: stringLocalizer.Object);

            var actionContext = new ActionContext();
            var context = new ClientModelValidationContext(actionContext, metadata, provider);

            // Act
            var rules = adapter.GetClientValidationRules(context);

            // Assert
            var rule = Assert.Single(rules);
            Assert.Equal("length", rule.ValidationType);
            Assert.Equal(1, rule.ValidationParameters.Count);
            Assert.Equal(8, rule.ValidationParameters["max"]);
            Assert.Equal(expectedMessage, rule.ErrorMessage);
        }
开发者ID:phinq19,项目名称:git_example,代码行数:32,代码来源:StringLengthAttributeAdapterTest.cs

示例7: Filter_SkipsAntiforgeryVerification_WhenOverridden

        public async Task Filter_SkipsAntiforgeryVerification_WhenOverridden()
        {
            // Arrange
            var antiforgery = new Mock<IAntiforgery>(MockBehavior.Strict);
            antiforgery
                .Setup(a => a.ValidateRequestAsync(It.IsAny<HttpContext>()))
                .Returns(Task.FromResult(0))
                .Verifiable();

            var filter = new ValidateAntiforgeryTokenAuthorizationFilter(antiforgery.Object, NullLoggerFactory.Instance);

            var actionContext = new ActionContext(new DefaultHttpContext(), new RouteData(), new ActionDescriptor());
            actionContext.HttpContext.Request.Method = "POST";

            var context = new AuthorizationContext(actionContext, new IFilterMetadata[]
            {
                filter,
                new IgnoreAntiforgeryTokenAttribute(),
            });

            // Act
            await filter.OnAuthorizationAsync(context);

            // Assert
            antiforgery.Verify(a => a.ValidateRequestAsync(It.IsAny<HttpContext>()), Times.Never());
        }
开发者ID:phinq19,项目名称:git_example,代码行数:26,代码来源:ValidateAntiforgeryTokenAuthorizationFilterTest.cs

示例8: Validate

        /// <inheritdoc />
        public void Validate(
            ActionContext actionContext,
            IModelValidatorProvider validatorProvider,
            ValidationStateDictionary validationState,
            string prefix,
            object model)
        {
            if (actionContext == null)
            {
                throw new ArgumentNullException(nameof(actionContext));
            }

            if (validatorProvider == null)
            {
                throw new ArgumentNullException(nameof(validatorProvider));
            }

            var visitor = new ValidationVisitor(
                actionContext,
                validatorProvider,
                _validatorCache,
                _modelMetadataProvider,
                validationState);

            var metadata = model == null ? null : _modelMetadataProvider.GetMetadataForType(model.GetType());
            visitor.Validate(metadata, prefix, model);
        }
开发者ID:cemalshukriev,项目名称:Mvc,代码行数:28,代码来源:DefaultObjectValidator.cs

示例9: OnActionExecuting

        /// <summary>
        /// 验证是否登录,Code返回1为没有登录或者token失效,要重新登录
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override bool OnActionExecuting(ActionContext context)
        {
            LogonBLL logonbll = new LogonBLL();
            UserBLL userbll = new UserBLL();
            //验证没有token
            if (!context.Parameters.ContainsKey("token") || context.Parameters["token"] == null)
            {
                this.Message = "没有token!";
                context.Code = 2;
                return false;
            }
            //验证有没有登录
            string token = context.Parameters["token"].ToString();

            int result = userbll.CheckUserAuth(token);
            switch (result)
            {
                case 3:
                    this.Message = "token失效,请重新登录!";
                    context.Code = result;
                    return false;
                case 4:
                    this.Message = "您没有权限进行该操作!";
                    context.Code = result;
                    return false;
            }

            return true;
        }
开发者ID:franknew,项目名称:RiskMgr,代码行数:34,代码来源:AuthFilter.cs

示例10: OnAuthentication

        public override void OnAuthentication(ActionContext actionContext)
        {
            var request = actionContext.Request;
            if (request == null)
                return;

            var deviceId = (string)request["deviceId"];
            var deviceKey = (string)request["deviceKey"];
            if (deviceId == null || deviceKey == null)
                return;

            var controller = (DeviceHive.WebSockets.API.Controllers.ControllerBase)actionContext.Controller;
            var device = controller.DataContext.Device.Get(deviceId);
            if (device == null || device.Key == null || device.Key != deviceKey)
            {
                if (ThrowDeviceNotFoundException)
                    throw new WebSocketRequestException("Device not found");
                return;
            }

            if (device.IsBlocked)
                throw new WebSocketRequestException("Device is blocked");

            controller.DataContext.Device.SetLastOnline(device.ID);
            actionContext.Parameters["AuthDevice"] = device;
        }
开发者ID:bestpetrovich,项目名称:devicehive-.net,代码行数:26,代码来源:AuthenticateDeviceAttribute.cs

示例11: AddValidation_WithLocalization

        public void AddValidation_WithLocalization()
        {
            // Arrange
            var provider = TestModelMetadataProvider.CreateDefaultProvider();
            var metadata = provider.GetMetadataForProperty(typeof(string), "Length");

            var attribute = new RangeAttribute(typeof(decimal), "0", "100");
            attribute.ErrorMessage = "The field Length must be between {1} and {2}.";

            var expectedProperties = new object[] { "Length", 0m, 100m };
            var expectedMessage = "The field Length must be between 0 and 100.";

            var stringLocalizer = new Mock<IStringLocalizer>();
            stringLocalizer
                .Setup(s => s[attribute.ErrorMessage, expectedProperties])
                .Returns(new LocalizedString(attribute.ErrorMessage, expectedMessage));

            var adapter = new RangeAttributeAdapter(attribute, stringLocalizer: stringLocalizer.Object);

            var actionContext = new ActionContext();
            var context = new ClientModelValidationContext(actionContext, metadata, provider, new AttributeDictionary());

            // Act
            adapter.AddValidation(context);

            // Assert
            Assert.Collection(
                context.Attributes,
                kvp => { Assert.Equal("data-val", kvp.Key); Assert.Equal("true", kvp.Value); },
                kvp => { Assert.Equal("data-val-range", kvp.Key); Assert.Equal(expectedMessage, kvp.Value); },
                kvp => { Assert.Equal("data-val-range-max", kvp.Key); Assert.Equal("100", kvp.Value); },
                kvp => { Assert.Equal("data-val-range-min", kvp.Key); Assert.Equal("0", kvp.Value); });
        }
开发者ID:ymd1223,项目名称:Mvc,代码行数:33,代码来源:RangeAttributeAdapterTest.cs

示例12: OnActionExecuting

        /// <summary>
        /// Called by the ASP.NET MVC framework before the action method executes.
        /// </summary>
        /// <param name="filterContext">The filter context.</param>
        /// <exception cref="BeetleException">BeetleActionFilterAttribute should only be applied to Queryable actions.</exception>
        public override void OnActionExecuting(ActionExecutingContext filterContext) {
            base.OnActionExecuting(filterContext);

            var controller = filterContext.Controller;
            var action = filterContext.ActionDescriptor;
            var reflectedAction = action as ReflectedActionDescriptor;
            var actionMethod = reflectedAction != null 
                ? reflectedAction.MethodInfo 
                : controller.GetType().GetMethod(action.ActionName);

            var service = controller as IBeetleService;
            if (_beetleConfig == null)
                _beetleConfig = service != null ? service.BeetleConfig : BeetleConfig.Instance;

            string queryString;
            NameValueCollection queryParams;
            object[] actionArgs;
            // handle request message
            GetParameters(filterContext, out queryString, out queryParams, out actionArgs);

            // execute the action method
            var contentValue = actionMethod.Invoke(controller, actionArgs);
            // get client hash
            // process the request and return the result
            var actionContext = new ActionContext(action.ActionName, contentValue, queryString, queryParams, MaxResultCount, CheckRequestHashNullable);
            var processResult = ProcessRequest(contentValue, actionContext, service);
            // handle response message
            filterContext.Result = HandleResponse(filterContext, processResult);
        }
开发者ID:amartelr,项目名称:Beetle.js,代码行数:34,代码来源:BeetleActionFilterAttribute.cs

示例13: RedirectToAction_Execute_PassesCorrectValuesToRedirect

        public async void RedirectToAction_Execute_PassesCorrectValuesToRedirect()
        {
            // Arrange
            var expectedUrl = "SampleAction";
            var expectedPermanentFlag = false;
            var httpContext = new Mock<HttpContext>();
            var httpResponse = new Mock<HttpResponse>();
            httpContext.Setup(o => o.Response).Returns(httpResponse.Object);
            httpContext.Setup(o => o.RequestServices.GetService(typeof(ITempDataDictionary)))
                .Returns(Mock.Of<ITempDataDictionary>());

            var actionContext = new ActionContext(httpContext.Object,
                                                  new RouteData(),
                                                  new ActionDescriptor());
            var urlHelper = GetMockUrlHelper(expectedUrl);
            var result = new RedirectToActionResult("SampleAction", null, null)
            {
                UrlHelper = urlHelper,
            };

            // Act
            await result.ExecuteResultAsync(actionContext);

            // Assert
            // Verifying if Redirect was called with the specific Url and parameter flag.
            // Thus we verify that the Url returned by UrlHelper is passed properly to
            // Redirect method and that the method is called exactly once.
            httpResponse.Verify(r => r.Redirect(expectedUrl, expectedPermanentFlag), Times.Exactly(1));
        }
开发者ID:njannink,项目名称:sonarlint-vs,代码行数:29,代码来源:RedirectToActionResultTest.cs

示例14: GetViewDataDictionary

 private ViewDataDictionary GetViewDataDictionary(ActionContext context)
 {
     var serviceProvider = context.HttpContext.RequestServices;
     return new ViewDataDictionary(
         _modelMetadataProvider,
         context.ModelState);
 }
开发者ID:4myBenefits,项目名称:Mvc,代码行数:7,代码来源:ViewDataDictionaryControllerPropertyActivator.cs

示例15: Activate_SetsPropertiesFromActionContextHierarchy

        public void Activate_SetsPropertiesFromActionContextHierarchy()
        {
            // Arrange
            var httpRequest = Mock.Of<HttpRequest>();
            var httpContext = new Mock<HttpContext>();
            httpContext.SetupGet(c => c.Request)
                       .Returns(httpRequest);
            httpContext.SetupGet(c => c.RequestServices)
                       .Returns(Mock.Of<IServiceProvider>());
            var routeContext = new RouteContext(httpContext.Object);
            var controller = new TestController();
            var context = new ActionContext(routeContext, new ActionDescriptor())
            {
                Controller = controller
            };
            var activator = new DefaultControllerActivator();

            // Act
            activator.Activate(controller, context);

            // Assert
            Assert.Same(context, controller.ActionContext);
            Assert.Same(httpContext.Object, controller.HttpContext);
            Assert.Same(httpRequest, controller.GetHttpRequest());
        }
开发者ID:Nakro,项目名称:Mvc,代码行数:25,代码来源:DefaultControllerActivatorTest.cs


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