Ejemplo n.º 1
0
        public async Task ExecuteResultAsync(ActionContext actionContext) {
            using (_pipe) {
                var context = actionContext.HttpContext;
                var httpResponse = context.Features.Get<IHttpResponseFeature>();

                if (!context.WebSockets.IsWebSocketRequest) {
                    httpResponse.ReasonPhrase = "Websocket connection expected";
                    httpResponse.StatusCode = 401;
                    return;
                }

                using (var socket = await context.WebSockets.AcceptWebSocketAsync("Microsoft.R.Host")) {
                    Task wsToPipe, pipeToWs, completed;

                    var cts = CancellationTokenSource.CreateLinkedTokenSource(context.RequestAborted);
                    wsToPipe = WebSocketToPipeWorker(socket, _pipe, cts.Token);
                    pipeToWs = PipeToWebSocketWorker(socket, _pipe, cts.Token);
                    completed = await Task.WhenAny(wsToPipe, pipeToWs);

                    if (completed == pipeToWs) {
                        // If the pipe end is exhausted, tell the client that there's no more messages to follow,
                        // so that it can gracefully disconnect from its end. 
                        await socket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "", context.RequestAborted);
                    } else {
                        // If the client disconnected, then just cancel any outstanding reads from the pipe.
                        cts.Cancel();
                    }
                }
            }
        }
Ejemplo n.º 2
0
        public async Task ExecuteResultAsync_InvokesSignOutAsyncOnAuthenticationManager()
        {
            // Arrange
            var authenticationManager = new Mock<AuthenticationManager>();
            authenticationManager
                .Setup(c => c.SignOutAsync("", null))
                .Returns(TaskCache.CompletedTask)
                .Verifiable();
            var httpContext = new Mock<HttpContext>();
            httpContext.Setup(c => c.RequestServices).Returns(CreateServices());
            httpContext.Setup(c => c.Authentication).Returns(authenticationManager.Object);
            var result = new SignOutResult("", null);
            var routeData = new RouteData();

            var actionContext = new ActionContext(
                httpContext.Object,
                routeData,
                new ActionDescriptor());

            // Act
            await result.ExecuteResultAsync(actionContext);

            // Assert
            authenticationManager.Verify();
        }
Ejemplo n.º 3
0
        public IEnumerable<MenuItem> BuildMenu(string name, ActionContext actionContext)
        {
            var builder = new NavigationBuilder();

            // Processes all navigation builders to create a flat list of menu items.
            // If a navigation builder fails, it is ignored.
            foreach (var navigationProvider in _navigationProviders)
            {
                try
                {
                    navigationProvider.BuildNavigation(name, builder);
                }
                catch (Exception e)
                {
                    _logger.LogError($"An exception occured while building the menu: {name}", e);
                }
            }

            var menuItems = builder.Build();

            // Merge all menu hierarchies into a single one
            Merge(menuItems);

            // Remove unauthorized menu items
            menuItems = Reduce(menuItems, null);

            // Compute Url and RouteValues properties to Href
            menuItems = ComputeHref(menuItems, actionContext);

            return menuItems;
        }
        public async void RedirectToAction_Execute_PassesCorrectValuesToRedirect()
        {
            // Arrange
            var expectedUrl = "SampleAction";
            var expectedPermanentFlag = false;

            var httpContext = new Mock<HttpContext>();
            httpContext
                .SetupGet(o => o.RequestServices)
                .Returns(CreateServices().BuildServiceProvider());

            var httpResponse = new Mock<HttpResponse>();
            httpContext
                .Setup(o => o.Response)
                .Returns(httpResponse.Object);

            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));
        }
Ejemplo n.º 5
0
		public override async Task ExecuteResultAsync(ActionContext context)
		{
			var response = context.HttpContext.Response;
			response.ContentType = ContentType;
			var targetStream = response.Body;
			if (CopyStream != null)
			{
				await Task.Factory.StartNew(() =>
				{
					CopyStream(targetStream);
				});
			}
			else if (Content != null)
			{
				await targetStream.WriteAsync(Content, 0, Content.Length);

			}
			else
			{
				using (SourceStream)
				{
					if (SourceStream.CanSeek)
					{
						SourceStream.Seek(0, SeekOrigin.Begin);
					}
					await SourceStream.CopyToAsync(targetStream);
				}
			}
		}
Ejemplo n.º 6
0
        public override Task ExecuteResultAsync(ActionContext context)
        {
            var executor = context.HttpContext.RequestServices.GetRequiredService<ObjectResultExecutor>();
            var result =  executor.ExecuteAsync(context, this);

            return result;
        }
Ejemplo n.º 7
0
        /// <summary>
        /// 覆盖 JsonResult 的方法;
        /// </summary>
        /// <param name="context"></param>
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            HttpResponseBase response = context.HttpContext.Response;

            if (!string.IsNullOrEmpty(this.ContentType))
            {
                response.ContentType = this.ContentType;
            }
            else
            {
                response.ContentType = "application/json";
            }
            var data = this.GetJsonResultValue();

            if (data != null)
            {
                IsoDateTimeConverter timeConvert = new IsoDateTimeConverter();
                timeConvert.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
                string content = "";
                if (data is SerializeToJson)
                {
                    content = ((SerializeToJson)data).SerializeToJson();
                }
                else
                {
                    content = JsonConvert.SerializeObject(content, Newtonsoft.Json.Formatting.None, timeConvert);
                }
                response.Write(content);
            }
        }
        public async Task InvalidModelStateResult_WritesHttpError()
        {
            // Arrange
            var httpContext = new DefaultHttpContext();
            httpContext.RequestServices = CreateServices();

            var stream = new MemoryStream();
            httpContext.Response.Body = stream;

            var context = new ActionContext(httpContext, new RouteData(), new ActionDescriptor());

            var modelState = new ModelStateDictionary();
            modelState.AddModelError("product.Name", "Name is required.");

            var expected =
                "{\"Message\":\"The request is invalid.\"," +
                "\"ModelState\":{\"product.Name\":[\"Name is required.\"]}}";

            var result = new InvalidModelStateResult(modelState, includeErrorDetail: false);

            // Act
            await result.ExecuteResultAsync(context);

            // Assert
            using (var reader = new StreamReader(stream))
            {
                stream.Seek(0, SeekOrigin.Begin);
                var content = reader.ReadToEnd();
                Assert.Equal(expected, content);
            }
        }
Ejemplo n.º 9
0
        public async Task ExecuteResultAsync_InvokesSignInAsyncOnConfiguredScheme()
        {
            // Arrange
            var principal = new ClaimsPrincipal();
            var authProperties = new AuthenticationProperties();
            var authenticationManager = new Mock<AuthenticationManager>();
            authenticationManager
                .Setup(c => c.SignInAsync("Scheme1", principal, authProperties))
                .Returns(TaskCache.CompletedTask)
                .Verifiable();
            var httpContext = new Mock<HttpContext>();
            httpContext.Setup(c => c.RequestServices).Returns(CreateServices());
            httpContext.Setup(c => c.Authentication).Returns(authenticationManager.Object);
            var result = new SignInResult("Scheme1", principal, authProperties);
            var routeData = new RouteData();

            var actionContext = new ActionContext(
                httpContext.Object,
                routeData,
                new ActionDescriptor());

            // Act
            await result.ExecuteResultAsync(actionContext);

            // Assert
            authenticationManager.Verify();
        }
Ejemplo n.º 10
0
        public async Task ExecuteResultAsync_FallsBackToWebRootFileProvider_IfNoFileProviderIsPresent()
        {
            // Arrange
            var path = Path.Combine("TestFiles", "FilePathResultTestFile.txt");
            var result = new TestVirtualFileResult(path, "text/plain");

            var appEnvironment = new Mock<IHostingEnvironment>();
            appEnvironment.Setup(app => app.WebRootFileProvider)
                .Returns(GetFileProvider(path));

            var httpContext = GetHttpContext();
            httpContext.Response.Body = new MemoryStream();
            httpContext.RequestServices = new ServiceCollection()
                .AddSingleton<IHostingEnvironment>(appEnvironment.Object)
                .AddTransient<ILoggerFactory, LoggerFactory>()
                .BuildServiceProvider();
            var context = new ActionContext(httpContext, new RouteData(), new ActionDescriptor());

            // Act
            await result.ExecuteResultAsync(context);
            httpContext.Response.Body.Position = 0;

            // Assert
            Assert.NotNull(httpContext.Response.Body);
            var contents = await new StreamReader(httpContext.Response.Body).ReadToEndAsync();
            Assert.Equal("FilePathResultTestFile contents¡", contents);
        }
        private static ViewComponentContext GetViewComponentContext(IView view, Stream stream)
        {
            var actionContext = new ActionContext(new DefaultHttpContext(), new RouteData(), new ActionDescriptor());
            var viewData = new ViewDataDictionary(new EmptyModelMetadataProvider());
            var viewContext = new ViewContext(
                actionContext,
                view,
                viewData,
                new TempDataDictionary(actionContext.HttpContext, new SessionStateTempDataProvider()),
                TextWriter.Null,
                new HtmlHelperOptions());

            var writer = new StreamWriter(stream) { AutoFlush = true };

            var viewComponentDescriptor = new ViewComponentDescriptor()
            {
                TypeInfo = typeof(object).GetTypeInfo(),
            };

            var viewComponentContext = new ViewComponentContext(
                viewComponentDescriptor,
                new Dictionary<string, object>(),
                new HtmlTestEncoder(),
                viewContext,
                writer);

            return viewComponentContext;
        }
		private async Task ExecuteProblemResultAsync(HttpContext context, Problem problem)
		{
			var actionContext = new ActionContext(context, new RouteData(), new ActionDescriptor());
			var executor = context.RequestServices.GetService<ObjectResultExecutor>() ?? _objectResultExecutor;
			var result = new ProblemResult(problem);
			await result.ExecuteResultAsync(executor, actionContext);
		}
Ejemplo n.º 13
0
 public Task ExecuteResultAsync(ActionContext context)
 {
     context.HttpContext.Response.StatusCode = StatusCodes.Status200OK;
     context.HttpContext.Response.ContentType = "text/plain";
     context.HttpContext.Response.ContentLength = _helloWorldPayload.Length;
     return context.HttpContext.Response.Body.WriteAsync(_helloWorldPayload, 0, _helloWorldPayload.Length);
 }
Ejemplo n.º 14
0
        /// <inheritdoc />
        public override async Task ExecuteResultAsync(ActionContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (AuthenticationSchemes == null)
            {
                throw new InvalidOperationException(
                    Resources.FormatPropertyOfTypeCannotBeNull(
                        /* property: */ nameof(AuthenticationSchemes),
                        /* type: */ nameof(SignOutResult)));
            }

            if (AuthenticationSchemes.Count == 0)
            {
                throw new ArgumentException(Resources.MustSpecifyAtLeastOneAuthenticationScheme, nameof(AuthenticationSchemes));
            }

            var loggerFactory = context.HttpContext.RequestServices.GetRequiredService<ILoggerFactory>();
            var logger = loggerFactory.CreateLogger<SignOutResult>();

            logger.SignOutResultExecuting(AuthenticationSchemes);

            var authentication = context.HttpContext.Authentication;
            
            for (var i = 0; i < AuthenticationSchemes.Count; i++)
            {
                await authentication.SignOutAsync(AuthenticationSchemes[i], Properties);
            }
        }
 public static ViewContext FromActionContext(HttpTestContext testContext, ActionContext actionContext)
     => FromViewContext(testContext, new ViewContext
     {
         HttpContext = actionContext.HttpContext,
         RouteData = actionContext.RouteData,
         ActionDescriptor = actionContext.ActionDescriptor,
     });
Ejemplo n.º 16
0
        public override Task ExecuteResultAsync(Microsoft.AspNetCore.Mvc.ActionContext context)
        {
            var ser   = this.jsonSerializer == null ? Never.Serialization.SerializeEnvironment.JsonSerializer : this.jsonSerializer;
            var ouput = ser.Serialize <T>(content);

            var jsoncallback = context.ActionDescriptor.RouteValues.ContainsKey("callback") ? context.ActionDescriptor.RouteValues["callback"] : null;

            if (jsoncallback != null && !string.IsNullOrEmpty(jsoncallback))
            {
                context.HttpContext.Response.ContentType = "application/x-javascript";
                using (var writer = new System.IO.StreamWriter(context.HttpContext.Response.Body))
                {
                    writer.Write(string.Format("{0}({1})", jsoncallback, ouput));
                }
            }
            else
            {
                context.HttpContext.Response.ContentType = "application/json";
                using (var writer = new System.IO.StreamWriter(context.HttpContext.Response.Body))
                {
                    writer.Write(string.Format("{0}", ouput));
                }
            }

            return(Task.CompletedTask);
        }
Ejemplo n.º 17
0
        public async Task WriteFileAsync_WritesResponse_InChunksOfFourKilobytes()
        {
            // Arrange
            var mockReadStream = new Mock<Stream>();
            mockReadStream.SetupSequence(s => s.ReadAsync(It.IsAny<byte[]>(), 0, 0x1000, CancellationToken.None))
                .Returns(Task.FromResult(0x1000))
                .Returns(Task.FromResult(0x500))
                .Returns(Task.FromResult(0));

            var mockBodyStream = new Mock<Stream>();
            mockBodyStream
                .Setup(s => s.WriteAsync(It.IsAny<byte[]>(), 0, 0x1000, CancellationToken.None))
                .Returns(Task.FromResult(0));

            mockBodyStream
                .Setup(s => s.WriteAsync(It.IsAny<byte[]>(), 0, 0x500, CancellationToken.None))
                .Returns(Task.FromResult(0));

            var result = new FileStreamResult(mockReadStream.Object, "text/plain");

            var httpContext = GetHttpContext();
            httpContext.Response.Body = mockBodyStream.Object;

            var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor());

            // Act
            await result.ExecuteResultAsync(actionContext);

            // Assert
            mockReadStream.Verify();
            mockBodyStream.Verify();
        }
Ejemplo n.º 18
0
        public async Task RedirectToAction_Execute_ThrowsOnNullUrl()
        {
            // Arrange
            var httpContext = new Mock<HttpContext>();
            httpContext
                .Setup(o => o.Response)
                .Returns(new Mock<HttpResponse>().Object);
            httpContext
                .SetupGet(o => o.RequestServices)
                .Returns(CreateServices().BuildServiceProvider());

            var actionContext = new ActionContext(httpContext.Object, new RouteData(), new ActionDescriptor());

            var urlHelper = GetMockUrlHelper(returnValue: null);
            var result = new RedirectToActionResult(null, null, null)
            {
                UrlHelper = urlHelper,
            };

            // Act & Assert
            await ExceptionAssert.ThrowsAsync<InvalidOperationException>(
                async () =>
                {
                    await result.ExecuteResultAsync(actionContext);
                },
                "No route matches the supplied values.");
        }
 public AuthorizationFilterTests()
 {
     ActionContext action = new ActionContext(Substitute.For<HttpContext>(), new RouteData(), new ActionDescriptor());
     context = new ResourceExecutingContext(action, new IFilterMetadata[0], new IValueProviderFactory[0]);
     authorization = Substitute.For<IAuthorizationProvider>();
     filter = new AuthorizationFilter(authorization);
 }
        public static HttpContextAccessor CreateHttpContextAccessor(RequestTelemetry requestTelemetry = null, ActionContext actionContext = null)
        {
            var services = new ServiceCollection();

            var request = new DefaultHttpContext().Request;
            request.Method = "GET";
            request.Path = new PathString("/Test");
            var contextAccessor = new HttpContextAccessor() { HttpContext = request.HttpContext };

            services.AddSingleton<IHttpContextAccessor>(contextAccessor);

            if (actionContext != null)
            {
                var si = new ActionContextAccessor();
                si.ActionContext = actionContext;
                services.AddSingleton<IActionContextAccessor>(si);
            }

            if (requestTelemetry != null)
            {
                services.AddSingleton<RequestTelemetry>(requestTelemetry);
            }

            IServiceProvider serviceProvider = services.BuildServiceProvider();
            contextAccessor.HttpContext.RequestServices = serviceProvider;

            return contextAccessor;
        }
Ejemplo n.º 21
0
 public override Task ExecuteResultAsync(ActionContext context) {
     var headers = context.HttpContext.Response.Headers;
     headers.Add(CustomHttpHeaders.RTVSApiError, new Extensions.Primitives.StringValues(_brokerApiError.ToString()));
     if (!string.IsNullOrEmpty(_message)) {
         headers.Add(CustomHttpHeaders.RTVSBrokerException, _message);
     }
     return base.ExecuteResultAsync(context);
 }
        public override Task RedirectToLogin(CookieRedirectContext context)
        {
            RouteData route = context.HttpContext.GetRouteData();
            ActionContext action = new ActionContext(context.HttpContext, route, new ActionDescriptor());
            context.RedirectUri = new UrlHelper(action).Action("Login", "Auth", new { area = "", returnUrl = context.Request.Path });

            return base.RedirectToLogin(context);
        }
 public override void ExecuteResult(ActionContext context)
 { 
     context.HttpContext.Response.ContentType = this.ContentType;
     if (Xml != null)
     {
         Xml.Save(context.HttpContext.Response.Body, SaveOptions.DisableFormatting);
     }
 }
Ejemplo n.º 24
0
 public TestResponseGenerator(IActionContextAccessor contextAccessor)
 {
     _actionContext = contextAccessor.ActionContext;
     if (_actionContext == null)
     {
         throw new InvalidOperationException("ActionContext should not be null here.");
     }
 }
        private void PrepareControllerContext(ActionContext actionContext)
        {
            this.HttpContext = actionContext.HttpContext;
            this.RouteData = actionContext.RouteData;
            this.ValueProviderFactories = this.ValueProviderFactories ?? new List<IValueProviderFactory>();

            TestHelper.SetActionContextToAccessor(this);
        }
Ejemplo n.º 26
0
        public override void ExecuteResult(ActionContext context)
        {
            var model = Mapper.Map(View.ViewData.Model, SourceType, DestinationType);

            View.ViewData.Model = model;

            View.ExecuteResult(context);
        }
        public void ExpandViewLocations_ReturnsViewLocations()
        {
            ActionContext context = new ActionContext(new DefaultHttpContext(), new RouteData(), new ActionDescriptor());
            ViewLocationExpanderContext expander = new ViewLocationExpanderContext(context, "Index", null, null, true);

            IEnumerable<String> expected = new[] { "/Views/{1}/{0}.cshtml", "/Views/Shared/{0}.cshtml" };
            IEnumerable<String> actual = new ViewLocationExpander().ExpandViewLocations(expander, null);

            Assert.Equal(expected, actual);
        }
Ejemplo n.º 28
0
        private IActionResult RedirectToUnauthorized(ActionContext context)
        {
            RouteValueDictionary route = new RouteValueDictionary();
            route["language"] = context.RouteData.Values["language"];
            route["action"] = "Unauthorized";
            route["controller"] = "Home";
            route["area"] = "";

            return new RedirectToRouteResult(route);
        }
Ejemplo n.º 29
0
        /// <inheritdoc />
        public override void ExecuteResult(ActionContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var executor = context.HttpContext.RequestServices.GetRequiredService<RedirectToRouteResultExecutor>();
            executor.Execute(context, this);
        }
		public async Task ExecuteResultAsync(ActionContext context)
		{
			context.HttpContext.Response.OnStarting(() => {
				SetResponseLinks(context.HttpContext.Response);
				SetResponseContentType(context.HttpContext.Response);
				return Task.FromResult(0);
			});

			await WriteContentAsync(context.HttpContext.Response);
		}
Ejemplo n.º 31
0
        /// <inheritdoc />
        public override Task ExecuteResultAsync(ActionContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var executor = context.HttpContext.RequestServices.GetRequiredService<VirtualFileResultExecutor>();
            return executor.ExecuteAsync(context, this);
        }
Ejemplo n.º 32
0
 /// <summary>
 /// Creates a new <see cref="ControllerContext"/>.
 /// </summary>
 /// <param name="context">The <see cref="ActionContext"/> associated with the current request.</param>
 public ControllerContext(ActionContext context)
     : base(context)
 {
     if (!(context.ActionDescriptor is ControllerActionDescriptor))
     {
         throw new ArgumentException(Resources.FormatActionDescriptorMustBeBasedOnControllerAction(
             typeof(ControllerActionDescriptor)),
             nameof(context));
     }
 }
Ejemplo n.º 33
0
        public override Task ExecuteAsync(Microsoft.AspNetCore.Mvc.ActionContext context, JsonResult result)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            if (result == null)
            {
                throw new ArgumentNullException("result");
            }

            var response = context.HttpContext.Response;

            ResponseContentTypeHelper.ResolveContentTypeAndEncoding(
                result.ContentType,
                response.ContentType,
                DefaultContentType,
                out var resolvedContentType,
                out var resolvedContentTypeEncoding);

            response.ContentType = resolvedContentType;

            if (result.Value != null)
            {
                using (var writer = WriterFactory.CreateWriter(response.Body, resolvedContentTypeEncoding))
                {
                    JsonSerializeOption option = null;
                    if (result is JsonResultWrapper wrapper)
                    {
                        option = wrapper.Option;
                    }

                    option = option ?? new JsonSerializeOption();

                    var globalconverters = GlobalSetting.Converters.Where(s => s is JsonConverter).Cast <JsonConverter>();
                    option.Converters.AddRange(globalconverters);

                    var serializer = new JsonSerializer(option);
                    using (var jsonWriter = new JsonWriter(writer))
                    {
                        serializer.Serialize(result.Value, jsonWriter);
                    }
                }
            }

            return(Task.CompletedTask);
        }
Ejemplo n.º 34
0
        /// <summary>
        /// 获取Model的错误信息
        /// </summary>
        /// <param name="actionContext"></param>
        /// <returns></returns>
        public static string ModelErrorMessage(this Microsoft.AspNetCore.Mvc.ActionContext actionContext)
        {
            if (actionContext.ModelState.IsValid)
            {
                return(string.Empty);
            }

            if (actionContext.ModelState.Any() && actionContext.ModelState.Keys.Any())
            {
                foreach (var key in actionContext.ModelState.Keys)
                {
                    var errors = actionContext.ModelState[key];
                    if (errors != null && errors.Errors != null && errors.Errors.Any())
                    {
                        foreach (var e in errors.Errors)
                        {
                            return(e.ErrorMessage);
                        }
                    }
                }
            }

            return(string.Empty);
        }
Ejemplo n.º 35
0
        /// <summary>
        /// model验证错误信息
        /// </summary>
        public static IEnumerable <Never.Web.Mvc.Controllers.BasicController.ModelStateError> ModelError(this Microsoft.AspNetCore.Mvc.ActionContext actionContext)
        {
            if (actionContext.ModelState.IsValid)
            {
                yield break;
            }

            if (actionContext.ModelState.Any() && actionContext.ModelState.Keys.Any())
            {
                foreach (var key in actionContext.ModelState.Keys)
                {
                    var errors = actionContext.ModelState[key];
                    if (errors != null && errors.Errors != null && errors.Errors.Any())
                    {
                        foreach (var e in errors.Errors)
                        {
                            yield return(new Never.Web.Mvc.Controllers.BasicController.ModelStateError()
                            {
                                Exception = e.Exception,
                                Message = e.ErrorMessage,
                                MemberName = key
                            });
                        }
                    }
                }
            }

            yield break;
        }