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


C# Mvc.ActionContext类代码示例

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


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

示例1: ExecuteResultAsync

		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);
				}
			}
		}
开发者ID:petrsvihlik,项目名称:WopiHost,代码行数:29,代码来源:FileResult.cs

示例2: ExecuteResultAsync_InvokesSignOutAsyncOnAuthenticationManager

        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();
        }
开发者ID:cemalshukriev,项目名称:Mvc,代码行数:25,代码来源:SignOutResultTest.cs

示例3: InvalidModelStateResult_WritesHttpError

        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);
            }
        }
开发者ID:cemalshukriev,项目名称:Mvc,代码行数:31,代码来源:InvalidModelStateResultTest.cs

示例4: ExecuteResultAsync

        public override Task ExecuteResultAsync(ActionContext context)
        {
            var executor = context.HttpContext.RequestServices.GetRequiredService<ObjectResultExecutor>();
            var result =  executor.ExecuteAsync(context, this);

            return result;
        }
开发者ID:ymd1223,项目名称:Mvc,代码行数:7,代码来源:ObjectResult.cs

示例5: FromActionContext

 public static ViewContext FromActionContext(HttpTestContext testContext, ActionContext actionContext)
     => FromViewContext(testContext, new ViewContext
     {
         HttpContext = actionContext.HttpContext,
         RouteData = actionContext.RouteData,
         ActionDescriptor = actionContext.ActionDescriptor,
     });
开发者ID:ivaylokenov,项目名称:MyTested.AspNetCore.Mvc,代码行数:7,代码来源:ViewContextMock.cs

示例6: ExecuteResultAsync

        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();
                    }
                }
            }
        }
开发者ID:Microsoft,项目名称:RTVS,代码行数:30,代码来源:WebSocketPipeAction.cs

示例7: BuildMenu

        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;
        }
开发者ID:jchenga,项目名称:Orchard2,代码行数:31,代码来源:NavigationManager.cs

示例8: WriteFileAsync_WritesResponse_InChunksOfFourKilobytes

        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();
        }
开发者ID:xuchrist,项目名称:Mvc,代码行数:32,代码来源:FileStreamResultTest.cs

示例9: RedirectToAction_Execute_PassesCorrectValuesToRedirect

        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));
        }
开发者ID:cemalshukriev,项目名称:Mvc,代码行数:33,代码来源:RedirectToActionResultTest.cs

示例10: CreateHttpContextAccessor

        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;
        }
开发者ID:RehanSaeed,项目名称:ApplicationInsights-aspnetcore,代码行数:28,代码来源:HttpContextAccessorHelper.cs

示例11: ExecuteResultAsync_InvokesSignInAsyncOnConfiguredScheme

        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();
        }
开发者ID:ymd1223,项目名称:Mvc,代码行数:27,代码来源:SignInResultTest.cs

示例12: ExecuteProblemResultAsync

		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);
		}
开发者ID:MakingSense,项目名称:aspnet-hypermedia-api,代码行数:7,代码来源:ApiErrorHandlerMiddleware.cs

示例13: ExecuteResultAsync_FallsBackToWebRootFileProvider_IfNoFileProviderIsPresent

        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);
        }
开发者ID:cemalshukriev,项目名称:Mvc,代码行数:27,代码来源:VirtualFileResultTest.cs

示例14: ExecuteResultAsync

 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);
 }
开发者ID:nathana1,项目名称:FrameworkBenchmarks,代码行数:7,代码来源:HomeController.cs

示例15: ExecuteResultAsync

        /// <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);
            }
        }
开发者ID:cemalshukriev,项目名称:Mvc,代码行数:33,代码来源:SignOutResult.cs


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