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); }); }
public void CreateController_UsesControllerActivatorToInstantiateController() { // Arrange var expected = new MyController(); var actionDescriptor = new ControllerActionDescriptor { ControllerTypeInfo = typeof(MyController).GetTypeInfo() }; var httpContext = new DefaultHttpContext(); httpContext.RequestServices = GetServices(); var actionContext = new ActionContext(httpContext, new RouteData(), actionDescriptor); var activator = new Mock<IControllerActivator>(); activator.Setup(a => a.Create(actionContext, typeof(MyController))) .Returns(expected) .Verifiable(); var controllerFactory = new DefaultControllerFactory(activator.Object); // Act var result = controllerFactory.CreateController(actionContext); // Assert var controller = Assert.IsType<MyController>(result); Assert.Same(expected, controller); activator.Verify(); }
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); }
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)); }
public void GetClientValidationRules_ReturnsValidationParameters_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); // Act var rules = adapter.GetClientValidationRules(context); // Assert var rule = Assert.Single(rules); Assert.Equal("required", rule.ValidationType); Assert.Empty(rule.ValidationParameters); Assert.Equal(expectedMessage, rule.ErrorMessage); }
public void ClientRulesWithCompareAttribute_ErrorMessageUsesDisplayName() { // Arrange var metadataProvider = TestModelMetadataProvider.CreateDefaultProvider(); var metadata = metadataProvider.GetMetadataForProperty(typeof(PropertyDisplayNameModel), "MyProperty"); var attribute = new CompareAttribute("OtherProperty"); attribute.ErrorMessage = "CompareAttributeErrorMessage"; var stringLocalizer = new Mock<IStringLocalizer>(); var expectedProperties = new object[] { "MyPropertyDisplayName", "OtherPropertyDisplayName" }; var expectedMessage = "'MyPropertyDisplayName' and 'OtherPropertyDisplayName' do not match."; stringLocalizer.Setup(s => s[attribute.ErrorMessage, expectedProperties]) .Returns(new LocalizedString(attribute.ErrorMessage, expectedMessage)); var adapter = new CompareAttributeAdapter(attribute, stringLocalizer: stringLocalizer.Object); var actionContext = new ActionContext(); var context = new ClientModelValidationContext(actionContext, metadata, metadataProvider); // Act var rules = adapter.GetClientValidationRules(context); // Assert var rule = Assert.Single(rules); // Mono issue - https://github.com/aspnet/External/issues/19 Assert.Equal(expectedMessage, rule.ErrorMessage); }
/// <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); }
public void OnActionExecuted_HandlesExceptionAndReturnsObjectResult() { // Arrange var filter = new HttpResponseExceptionActionFilter(); var httpContext = new DefaultHttpContext(); httpContext.Request.Method = "GET"; var actionContext = new ActionContext( httpContext, new RouteData(), Mock.Of<ActionDescriptor>()); var context = new ActionExecutedContext( actionContext, filters: new List<IFilter>(), controller: new object()); context.Exception = new HttpResponseException(HttpStatusCode.BadRequest); // Act filter.OnActionExecuted(context); // Assert Assert.True(context.ExceptionHandled); var result = Assert.IsType<ObjectResult>(context.Result); Assert.Equal(typeof(HttpResponseMessage), result.DeclaredType); var response = Assert.IsType<HttpResponseMessage>(result.Value); Assert.NotNull(response.RequestMessage); Assert.Equal(context.HttpContext.GetHttpRequestMessage(), response.RequestMessage); Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); }
public void SelectResponseCharacterEncoding_SelectsEncoding(string acceptCharsetHeaders, string requestEncoding, string[] supportedEncodings, string expectedEncoding) { // Arrange var mockHttpContext = new Mock<HttpContext>(); var httpRequest = new DefaultHttpContext().Request; httpRequest.Headers["Accept-Charset"] = acceptCharsetHeaders; httpRequest.ContentType = "application/acceptCharset;charset=" + requestEncoding; mockHttpContext.SetupGet(o => o.Request).Returns(httpRequest); var actionContext = new ActionContext(mockHttpContext.Object, new RouteData(), new ActionDescriptor()); var formatter = new TestOutputFormatter(); foreach (string supportedEncoding in supportedEncodings) { formatter.SupportedEncodings.Add(Encoding.GetEncoding(supportedEncoding)); } var formatterContext = new OutputFormatterContext() { Object = "someValue", ActionContext = actionContext, DeclaredType = typeof(string) }; // Act var actualEncoding = formatter.SelectCharacterEncoding(formatterContext); // Assert Assert.Equal(Encoding.GetEncoding(expectedEncoding), actualEncoding); }
private async Task WriteFileAsync(ActionContext context, PhysicalFileResult result) { var response = context.HttpContext.Response; if (!Path.IsPathRooted(result.FileName)) { throw new NotSupportedException(Resources.FormatFileResult_PathNotRooted(result.FileName)); } var sendFile = response.HttpContext.Features.Get<IHttpSendFileFeature>(); if (sendFile != null) { await sendFile.SendFileAsync( result.FileName, offset: 0, count: null, cancellation: default(CancellationToken)); } else { var fileStream = GetFileStream(result.FileName); using (fileStream) { await fileStream.CopyToAsync(response.Body, DefaultBufferSize); } } }
/// <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; }
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()); }
/// <summary> /// Attempts to find the <see cref="IView"/> associated with <paramref name="viewResult"/>. /// </summary> /// <param name="actionContext">The <see cref="ActionContext"/> associated with the current request.</param> /// <param name="viewResult">The <see cref="PartialViewResult"/>.</param> /// <returns>A <see cref="ViewEngineResult"/>.</returns> public virtual ViewEngineResult FindView(ActionContext actionContext, PartialViewResult viewResult) { if (actionContext == null) { throw new ArgumentNullException(nameof(actionContext)); } if (viewResult == null) { throw new ArgumentNullException(nameof(viewResult)); } var viewEngine = viewResult.ViewEngine ?? ViewEngine; var viewName = viewResult.ViewName ?? actionContext.ActionDescriptor.Name; var result = viewEngine.FindPartialView(actionContext, viewName); if (result.Success) { DiagnosticSource.ViewFound(actionContext, true, viewResult, viewName, result.View); Logger.LogVerbose("The partial view '{PartialViewName}' was found.", viewName); } else { DiagnosticSource.ViewNotFound(actionContext, true, viewResult, viewName, result.SearchedLocations); Logger.LogError( "The partial view '{PartialViewName}' was not found. Searched locations: {SearchedViewLocations}", viewName, result.SearchedLocations); } return result; }
/// <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); }
public void AddValidation_DoesNotTrounceExistingAttributes() { // Arrange var propertyName = "Length"; var provider = TestModelMetadataProvider.CreateDefaultProvider(); var metadata = provider.GetMetadataForProperty(typeof(string), propertyName); var attribute = new MinLengthAttribute(2) { ErrorMessage = "Array must have at least {1} items." }; var adapter = new MinLengthAttributeAdapter(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-minlength", "original"); context.Attributes.Add("data-val-minlength-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-minlength", kvp.Key); Assert.Equal("original", kvp.Value); }, kvp => { Assert.Equal("data-val-minlength-min", kvp.Key); Assert.Equal("original", kvp.Value); }); }
public void AddValidation_DoesNotTrounceExistingAttributes() { // Arrange var provider = TestModelMetadataProvider.CreateDefaultProvider(); var metadata = provider.GetMetadataForProperty(typeof(string), "Length"); var attribute = new StringLengthAttribute(10) { MinimumLength = 3 }; var adapter = new StringLengthAttributeAdapter(attribute, stringLocalizer: null); var expectedMessage = attribute.FormatErrorMessage("Length"); var actionContext = new ActionContext(); var context = new ClientModelValidationContext(actionContext, metadata, provider, new AttributeDictionary()); context.Attributes.Add("data-val", "original"); context.Attributes.Add("data-val-length", "original"); context.Attributes.Add("data-val-length-max", "original"); context.Attributes.Add("data-val-length-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-length", kvp.Key); Assert.Equal("original", kvp.Value); }, kvp => { Assert.Equal("data-val-length-max", kvp.Key); Assert.Equal("original", kvp.Value); }, kvp => { Assert.Equal("data-val-length-min", kvp.Key); Assert.Equal("original", kvp.Value); }); }
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()); }
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); }
public void Validate_SimpleType_MaxErrorsReached() { // Arrange var validatorProvider = CreateValidatorProvider(); var actionContext = new ActionContext(); var modelState = actionContext.ModelState; var validationState = new ValidationStateDictionary(); var validator = CreateValidator(); var model = (object)"test"; modelState.MaxAllowedErrors = 1; modelState.AddModelError("other.Model", "error"); modelState.SetModelValue("parameter", "test", "test"); validationState.Add(model, new ValidationStateEntry() { Key = "parameter" }); // Act validator.Validate(actionContext, validatorProvider, validationState, "parameter", model); // Assert Assert.False(modelState.IsValid); AssertKeysEqual(modelState, string.Empty, "parameter"); var entry = modelState["parameter"]; Assert.Equal(ModelValidationState.Skipped, entry.ValidationState); Assert.Empty(entry.Errors); }
private ViewDataDictionary GetViewDataDictionary(ActionContext context) { var serviceProvider = context.HttpContext.RequestServices; return new ViewDataDictionary( _modelMetadataProvider, context.ModelState); }
public void AddValidation_DoesNotTrounceExistingAttributes() { // Arrange var metadataProvider = TestModelMetadataProvider.CreateDefaultProvider(); var metadata = metadataProvider.GetMetadataForProperty(typeof(PropertyNameModel), "MyProperty"); var attribute = new CompareAttribute("OtherProperty"); var adapter = new CompareAttributeAdapter(attribute, stringLocalizer: null); var actionContext = new ActionContext(); var context = new ClientModelValidationContext( actionContext, metadata, metadataProvider, new AttributeDictionary()); context.Attributes.Add("data-val", "original"); context.Attributes.Add("data-val-equalto", "original"); context.Attributes.Add("data-val-equalto-other", "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-equalto", kvp.Key); Assert.Equal("original", kvp.Value); }, kvp => { Assert.Equal("data-val-equalto-other", kvp.Key); Assert.Equal("original", kvp.Value); }); }
public void Validate_SimpleReferenceType_Valid_WithPrefix() { // Arrange var validatorProvider = CreateValidatorProvider(); var actionContext = new ActionContext(); var modelState = actionContext.ModelState; var validationState = new ValidationStateDictionary(); var validator = CreateValidator(); var model = (object)"test"; modelState.SetModelValue("parameter", "test", "test"); validationState.Add(model, new ValidationStateEntry() { Key = "parameter" }); // Act validator.Validate(actionContext, validatorProvider, validationState, "parameter", model); // Assert Assert.True(modelState.IsValid); AssertKeysEqual(modelState, "parameter"); var entry = modelState["parameter"]; Assert.Equal(ModelValidationState.Valid, entry.ValidationState); Assert.Empty(entry.Errors); }
public void GetClientValidationRules_ReturnsValidationParameters() { // 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); // Act var rules = adapter.GetClientValidationRules(context); // Assert var rule = Assert.Single(rules); Assert.Equal("range", rule.ValidationType); Assert.Equal(2, rule.ValidationParameters.Count); Assert.Equal(0m, rule.ValidationParameters["min"]); Assert.Equal(100m, rule.ValidationParameters["max"]); Assert.Equal(expectedMessage, rule.ErrorMessage); }
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); }); }
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); }); }
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; }
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(); }
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); }
public void AddValidation_CorrectValidationTypeAndOverriddenErrorMessage() { // Arrange var expectedMessage = "Error message about 'DisplayId' from override."; var provider = new TestModelMetadataProvider(); provider .ForProperty(typeof(TypeWithNumericProperty), nameof(TypeWithNumericProperty.Id)) .BindingDetails(d => d.ModelBindingMessageProvider.ValueMustBeANumberAccessor = name => $"Error message about '{ name }' from override."); var metadata = provider.GetMetadataForProperty( typeof(TypeWithNumericProperty), nameof(TypeWithNumericProperty.Id)); var adapter = new NumericClientModelValidator(); 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-number", kvp.Key); Assert.Equal(expectedMessage, kvp.Value); }); }
public IValidationContext BeforeAspNetValidation(ActionContext actionContext, IValidationContext commonContext) { return(commonContext); }
public override void ExecuteResult(ActionContext context) { }
public async Task <IActionResult> InvokeAction(HttpContext httpContext, ModuleAction moduleAction, ActionContext actionContext) { IActionResult result = null; var targetController = _allControllers.FirstOrDefault(c => c.Namespace == moduleAction.ControllerNamespace && c.Name == moduleAction.ControllerName + ControllerTypeNameSuffix); if (targetController == null) { throw new Exception("Module Controller not found"); } var targetAction = targetController.GetMethods().FirstOrDefault(m => m.Name == moduleAction.ActionName); if (targetAction == null) { throw new Exception("Module Action not found"); } var executor = _cache.GetExecutor(targetAction, targetController); var actionArguments = new Dictionary <string, object>(StringComparer.OrdinalIgnoreCase); var arguments = PrepareArguments(actionArguments, executor); var returnType = executor.MethodReturnType; var controllerContext = new ControllerContext(actionContext); //var controller1 = _controllerFactory.CreateController(controllerContext); var serviceProvider = httpContext.RequestServices; var controller = _typeActivatorCache.CreateInstance <object>(serviceProvider, targetController.AsType()); //Returns foreach (var propertyActivator in _propertyActivators) { propertyActivator.Activate(controllerContext, controller); } //((Deviser.Core.Library.Controllers.DeviserController)controller).TempData = new TempDataDictionary() if (returnType == typeof(void)) { executor.Execute(controller, arguments); result = new EmptyResult(); } else if (returnType == typeof(Task)) { await(Task) executor.Execute(controller, arguments); result = new EmptyResult(); } else if (executor.TaskGenericType == typeof(IActionResult)) { result = await(Task <IActionResult>) executor.Execute(controller, arguments); if (result == null) { throw new InvalidOperationException( Resources.FormatActionResult_ActionReturnValueCannotBeNull(typeof(IActionResult))); } } else if (executor.IsTypeAssignableFromIActionResult) { if (executor.IsMethodAsync) { result = (IActionResult)await executor.ExecuteAsync(controller, arguments); } else { result = (IActionResult)executor.Execute(controller, arguments); } if (result == null) { throw new InvalidOperationException( Resources.FormatActionResult_ActionReturnValueCannotBeNull(executor.TaskGenericType ?? returnType)); } } else if (!executor.IsMethodAsync) { var resultAsObject = executor.Execute(controller, arguments); result = new ObjectResult(resultAsObject) { DeclaredType = returnType, }; } else if (executor.TaskGenericType != null) { var resultAsObject = await executor.ExecuteAsync(controller, arguments); result = new ObjectResult(resultAsObject) { DeclaredType = executor.TaskGenericType, }; } else { // This will be the case for types which have derived from Task and Task<T> or non Task types. throw new InvalidOperationException(Resources.FormatActionExecutor_UnexpectedTaskInstance( executor.MethodInfo.Name, executor.MethodInfo.DeclaringType)); } ((IDisposable)controller).RegisterForDispose(httpContext); return(result); }
public void Validate(ActionContext actionContext, ValidationStateDictionary validationState, string prefix, object model) { }
protected abstract IUrlHelper CreateUrlHelper(ActionContext actionContext);
public Task ExecuteResultAsync(ActionContext context) { context.HttpContext.Response.StatusCode = 200; context.HttpContext.Response.ContentType = "application/json"; return(context.HttpContext.Response.WriteAsync(_jsonString)); }
private void SetHeaders(ActionContext context) { context.HttpContext.Response.Headers.Add("ETag", "\"" + ETagValue + "\""); context.HttpContext.Response.Headers.Add("Access-Control-Expose-Headers", "Content-Length, ETag"); }
public override void ExecuteResult(ActionContext context) { SetHeaders(context); base.ExecuteResult(context); }
public override Task ExecuteResultAsync(ActionContext context) { SetHeaders(context); return(base.ExecuteResultAsync(context)); }
internal static Uri GetODataBatchBaseUri(this HttpRequest request, string oDataRouteName, IRouter route) { Contract.Assert(request != null); if (oDataRouteName == null) { // Return request's base address. return(new Uri(request.GetDisplayUrl())); } HttpContext context = request.HttpContext; #if !NETSTANDARD2_0 // Here's workaround to help "EndpointLinkGenerator" to generator ODataBatchPathMapping batchMapping = request.HttpContext.RequestServices.GetRequiredService <ODataBatchPathMapping>(); if (batchMapping.IsEndpointRouting) { context = new DefaultHttpContext { RequestServices = request.HttpContext.RequestServices, }; IEndpointFeature endpointFeature = new ODataEndpointFeature(); endpointFeature.Endpoint = new Endpoint((d) => null, null, "anything"); context.Features.Set(endpointFeature); context.Request.Scheme = request.Scheme; context.Request.Host = request.Host; } context.Request.ODataFeature().RouteName = oDataRouteName; #endif // The IActionContextAccessor and ActionContext will be present after routing but not before // GetUrlHelper only uses the HttpContext and the Router, which we have so construct a dummy // action context. ActionContext actionContext = new ActionContext { HttpContext = context, RouteData = new RouteData(), ActionDescriptor = new ActionDescriptor() }; actionContext.RouteData.Routers.Add(route); IUrlHelperFactory factory = request.HttpContext.RequestServices.GetRequiredService <IUrlHelperFactory>(); IUrlHelper helper = factory.GetUrlHelper(actionContext); RouteValueDictionary routeData = new RouteValueDictionary() { { ODataRouteConstants.ODataPath, String.Empty } }; RouteValueDictionary batchRouteData = request.ODataFeature().BatchRouteData; if (batchRouteData != null && batchRouteData.Any()) { foreach (var data in batchRouteData) { routeData.Add(data.Key, data.Value); } } string baseAddress = helper.Link(oDataRouteName, routeData); if (baseAddress == null) { throw new InvalidOperationException(SRResources.UnableToDetermineBaseUrl); } return(new Uri(baseAddress)); }
/// <summary> /// Attempts to find the <see cref="IView"/> associated with <paramref name="viewResult"/>. /// </summary> /// <param name="actionContext">The <see cref="ActionContext"/> associated with the current request.</param> /// <param name="viewResult">The <see cref="ViewResult"/>.</param> /// <returns>A <see cref="ViewEngineResult"/>.</returns> public virtual ViewEngineResult FindView(ActionContext actionContext, ViewResult viewResult) { if (actionContext == null) { throw new ArgumentNullException(nameof(actionContext)); } if (viewResult == null) { throw new ArgumentNullException(nameof(viewResult)); } var viewEngine = viewResult.ViewEngine ?? ViewEngine; var viewName = viewResult.ViewName ?? actionContext.ActionDescriptor.Name; var result = viewEngine.GetView(executingFilePath: null, viewPath: viewName, isMainPage: true); var originalResult = result; if (!result.Success) { result = viewEngine.FindView(actionContext, viewName, isMainPage: true); } if (!result.Success) { if (originalResult.SearchedLocations.Any()) { if (result.SearchedLocations.Any()) { // Return a new ViewEngineResult listing all searched locations. var locations = new List <string>(originalResult.SearchedLocations); locations.AddRange(result.SearchedLocations); result = ViewEngineResult.NotFound(viewName, locations); } else { // GetView() searched locations but FindView() did not. Use first ViewEngineResult. result = originalResult; } } } if (result.Success) { if (DiagnosticSource.IsEnabled("Microsoft.AspNet.Mvc.ViewFound")) { DiagnosticSource.Write( "Microsoft.AspNet.Mvc.ViewFound", new { actionContext = actionContext, isMainPage = true, result = viewResult, viewName = viewName, view = result.View, }); } Logger.ViewFound(viewName); } else { if (DiagnosticSource.IsEnabled("Microsoft.AspNet.Mvc.ViewNotFound")) { DiagnosticSource.Write( "Microsoft.AspNet.Mvc.ViewNotFound", new { actionContext = actionContext, isMainPage = true, result = viewResult, viewName = viewName, searchedLocations = result.SearchedLocations }); } Logger.ViewNotFound(viewName, result.SearchedLocations); } return(result); }
public async Task ExecuteResultAsync(ActionContext context) { await new JsonResult(this).ExecuteResultAsync(context); }
/// <summary> /// Executes the result operation of the action method synchronously. This method is called by MVC to process /// the result of an action method. /// </summary> /// <param name="context">The context in which the result is executed. The context information includes /// information about the action that was executed and request information.</param> public virtual void ExecuteResult(ActionContext context) { }
public ViewEngineResult FindView(ActionContext context, string viewName, bool isMainPage) { return null; }
public Task ExecuteResultAsync(ActionContext context) { return(new JsonResult(this).ExecuteResultAsync(context)); }
/// <summary> /// 获取视图 /// </summary> /// <param name="razorViewEngine">Razor视图引擎</param> /// <param name="actionContext">操作上下文</param> /// <param name="viewName">视图名</param> private ViewEngineResult GetView(IRazorViewEngine razorViewEngine, ActionContext actionContext, string viewName) { return(razorViewEngine.FindView(actionContext, viewName, true)); }
public virtual IServiceRunner <TRequest> CreateServiceRunner <TRequest>(ActionContext actionContext) { //cached per service action return(new ServiceRunner <TRequest>(this, actionContext)); }
/// <summary> /// Executes the result operation of the action method asynchronously. This method is called by MVC to process /// the result of an action method. /// The default implementation of this method calls the <see cref="ExecuteResult(ActionContext)"/> method and /// returns a completed task. /// </summary> /// <param name="context">The context in which the result is executed. The context information includes /// information about the action that was executed and request information.</param> /// <returns>A task that represents the asynchronous execute operation.</returns> public virtual Task ExecuteResultAsync(ActionContext context) { ExecuteResult(context); return(Task.CompletedTask); }
public static UnprocessableEntityObjectResult GetValidationErrorResult(Dictionary <string, List <string> > messages, ActionContext context) { var errors = new Dictionary <string, string[]>(); foreach (var message in messages) { errors.Add(message.Key, message.Value.ToArray()); } var problem = new ValidationProblemDetails(errors) { Type = "https://hmcr.bc.gov.ca/model-validation-error", Title = "One or more validation errors occurred.", Status = StatusCodes.Status422UnprocessableEntity, Detail = "Please refer to the errors property for additional details", Instance = context.HttpContext.Request.Path }; problem.Extensions.Add("traceId", context.HttpContext.TraceIdentifier); return(new UnprocessableEntityObjectResult(problem) { ContentTypes = { "application/problem+json" } }); }
public Task ExecuteResultAsync(ActionContext context) { return(innerResult.ExecuteResultAsync(context)); }
/// <summary> /// Executes the <see cref="JsonResult"/> and writes the response. /// </summary> /// <param name="context">The <see cref="ActionContext"/>.</param> /// <param name="result">The <see cref="JsonResult"/>.</param> /// <returns>A <see cref="Task"/> which will complete when writing has completed.</returns> public async Task ExecuteAsync(ActionContext context, JsonResult result) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (result == null) { throw new ArgumentNullException(nameof(result)); } var jsonSerializerSettings = GetSerializerSettings(result); var response = context.HttpContext.Response; ResponseContentTypeHelper.ResolveContentTypeAndEncoding( result.ContentType, response.ContentType, (DefaultContentType, Encoding.UTF8), MediaType.GetEncoding, out var resolvedContentType, out var resolvedContentTypeEncoding); response.ContentType = resolvedContentType; if (result.StatusCode != null) { response.StatusCode = result.StatusCode.Value; } Log.JsonResultExecuting(_logger, result.Value); var responseStream = response.Body; FileBufferingWriteStream?fileBufferingWriteStream = null; if (!_mvcOptions.SuppressOutputFormatterBuffering) { fileBufferingWriteStream = new FileBufferingWriteStream(); responseStream = fileBufferingWriteStream; } try { var value = result.Value; if (value != null && _asyncEnumerableReaderFactory.TryGetReader(value.GetType(), out var reader)) { Log.BufferingAsyncEnumerable(_logger, value); try { value = await reader(value, context.HttpContext.RequestAborted); } catch (OperationCanceledException) { } if (context.HttpContext.RequestAborted.IsCancellationRequested) { return; } } await using (var writer = _writerFactory.CreateWriter(responseStream, resolvedContentTypeEncoding)) { using var jsonWriter = new JsonTextWriter(writer); jsonWriter.ArrayPool = _charPool; jsonWriter.CloseOutput = false; jsonWriter.AutoCompleteOnClose = false; var jsonSerializer = JsonSerializer.Create(jsonSerializerSettings); jsonSerializer.Serialize(jsonWriter, value); } if (fileBufferingWriteStream != null) { await fileBufferingWriteStream.DrainBufferAsync(response.Body); } } finally { if (fileBufferingWriteStream != null) { await fileBufferingWriteStream.DisposeAsync(); } } }
private static ActionBindingContext GetActionBindingContext(MvcOptions options, ActionContext actionContext) { var valueProviderFactoryContext = new ValueProviderFactoryContext( actionContext.HttpContext, actionContext.RouteData.Values); var valueProvider = CompositeValueProvider.CreateAsync( options.ValueProviderFactories, valueProviderFactoryContext).Result; return(new ActionBindingContext() { InputFormatters = options.InputFormatters, OutputFormatters = options.OutputFormatters, // Not required for model binding. ValidatorProvider = new TestModelValidatorProvider(options.ModelValidatorProviders), ModelBinder = new CompositeModelBinder(options.ModelBinders), ValueProvider = valueProvider }); }
public async Task ExecuteResultAsync(ActionContext context) { await context.HttpContext.Response.WriteAsync("hello world"); }
public static UnprocessableEntityObjectResult GetServiceAreasMissingErrorResult(ActionContext context) { var problem = new ValidationProblemDetails(context.ModelState) { Type = "https://hmcr.bc.gov.ca/model-validation-error", Title = "Service areas missing", Status = StatusCodes.Status422UnprocessableEntity, Detail = "Please include service areas in the query string as comma separated string.", Instance = context.HttpContext.Request.Path }; problem.Extensions.Add("traceId", context.HttpContext.TraceIdentifier); return(new UnprocessableEntityObjectResult(problem) { ContentTypes = { "application/problem+json" } }); }
public override void ExecuteResult(ActionContext context) { Content = Feed.GetContent(); base.ExecuteResult(context); }
/// <summary> /// Attach all the response headers to the ActionContext /// </summary> private void AttachHeaders(ActionContext context) { context.PutETag(ETag); context.PutLastModified(LastModified); }
private static ContentFormat DetermineFormat(ActionContext context) => ContentFormat.For(EndpointType.BackOffice, context);
protected virtual async Task BatchCore() { var actionDescriptors = GetService <IActionDescriptorCollectionProvider>().ActionDescriptors; var actionInvokerFactory = GetService <IActionInvokerFactory>(); String basePath = ""; if (base.HttpContext.Request.PathBase.HasValue) { basePath = base.HttpContext.Request.PathBase; } else { int i = base.HttpContext.Request.Path.Value.IndexOf('/', 1); if (i > 0) { basePath = base.HttpContext.Request.Path.Value.Substring(0, i); } } Uri baseUri = UriHelper.GetBaseUri(base.Request); OeBatchMessage batchMessage = OeBatchMessage.CreateBatchMessage(EdmModel, baseUri, base.HttpContext.Request.Body, base.HttpContext.Request.ContentType); OeDataAdapter dataAdapter = null; Object dataContext = null; try { IEdmModel refModel = null; foreach (OeOperationMessage operation in batchMessage.Changeset) { if (dataContext == null) { refModel = EdmModel.GetEdmModel(operation.EntitySet.Container); dataAdapter = refModel.GetDataAdapter(operation.EntitySet.Container); dataContext = dataAdapter.CreateDataContext(); } OeEntitySetAdapter entitySetAdapter = refModel.GetEntitySetAdapter(operation.EntitySet); String path = basePath + "/" + entitySetAdapter.EntitySetName; List <ActionDescriptor> candidates = OeRouter.SelectCandidates(actionDescriptors.Items, base.RouteData.Values, path, operation.Method); if (candidates.Count > 1) { throw new AmbiguousActionException(String.Join(Environment.NewLine, candidates.Select(c => c.DisplayName))); } if (candidates.Count == 0) { throw new InvalidOperationException("Action " + operation.Method + " for controller " + basePath + " not found"); } Object entity; if (operation.Method == ODataConstants.MethodPatch) { var properties = new Dictionary <String, Object>(); foreach (ODataProperty odataProperty in operation.Entry.Properties) { PropertyInfo propertyInfo = entitySetAdapter.EntityType.GetProperty(odataProperty.Name); properties[odataProperty.Name] = OeEdmClrHelper.GetClrValue(propertyInfo.PropertyType, odataProperty.Value); } entity = properties; } else { entity = OeEdmClrHelper.CreateEntity(entitySetAdapter.EntityType, operation.Entry); } var modelState = new OeBatchFilterAttributeAttribute.BatchModelStateDictionary() { Entity = entity, DataContext = new OeDataContext(entitySetAdapter, refModel, dataContext, operation) }; OnBeforeInvokeController(modelState.DataContext, operation.Entry); var actionContext = new ActionContext(base.HttpContext, base.HttpContext.GetRouteData(), candidates[0], modelState); IActionInvoker actionInvoker = actionInvokerFactory.CreateInvoker(actionContext); await actionInvoker.InvokeAsync(); } await SaveChangesAsync(dataContext).ConfigureAwait(false); } finally { if (dataContext != null) { dataAdapter.CloseDataContext(dataContext); } } base.HttpContext.Response.ContentType = base.HttpContext.Request.ContentType; var batchWriter = new OeBatchWriter(EdmModel, baseUri); batchWriter.Write(base.HttpContext.Response.Body, batchMessage); }
public IActionInvoker CreateInvoker(ActionContext actionContext) { return(new CustomActionInvoker(actionContext)); }
public override Task ExecuteResultAsync(ActionContext context) { Content = Feed.GetContent(); return(base.ExecuteResultAsync(context)); }
public static void AfterActionMethod( this DiagnosticSource diagnosticSource, ActionContext actionContext, IDictionary<string, object> actionArguments, object controller, IActionResult result) { Debug.Assert(diagnosticSource != null); Debug.Assert(actionContext != null); Debug.Assert(actionArguments != null); Debug.Assert(controller != null); if (diagnosticSource.IsEnabled("Microsoft.AspNetCore.Mvc.AfterActionMethod")) { diagnosticSource.Write( "Microsoft.AspNetCore.Mvc.AfterActionMethod", new { actionContext = actionContext, arguments = actionArguments, controller = controller, result = result }); } }