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


C# Mvc.ActionContext类代码示例

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


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

示例1: GetViewDataDictionary

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

示例2: ExecuteResultAsync

        /// <inheritdoc />
        public override Task ExecuteResultAsync(ActionContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

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

            var response = context.HttpContext.Response;
            response.ContentType = ContentType.ToString();

            if (!string.IsNullOrEmpty(FileDownloadName))
            {
                // From RFC 2183, Sec. 2.3:
                // The sender may want to suggest a filename to be used if the entity is
                // detached and stored in a separate file. If the receiving MUA writes
                // the entity to a file, the suggested filename should be used as a
                // basis for the actual filename, where possible.
                var contentDisposition = new ContentDispositionHeaderValue("attachment");
                contentDisposition.SetHttpFileName(FileDownloadName);
                context.HttpContext.Response.Headers[HeaderNames.ContentDisposition] = contentDisposition.ToString();
            }

            logger.FileResultExecuting(FileDownloadName);
            return WriteFileAsync(response);
        }
开发者ID:phinq19,项目名称:git_example,代码行数:29,代码来源:FileResult.cs

示例3: Create_TypeActivatesTypesWithServices

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

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

示例4: ExecuteResultAsync_FallsBackToThePhysicalFileProvider_IfNoFileProviderIsPresent

        public async Task ExecuteResultAsync_FallsBackToThePhysicalFileProvider_IfNoFileProviderIsPresent()
        {
            // Arrange
            var path = Path.Combine("TestFiles", "FilePathResultTestFile.txt");
            var result = new FilePathResult(path, "text/plain");

            var appEnvironment = new Mock<IHostingEnvironment>();
            appEnvironment.Setup(app => app.WebRootFileProvider)
                .Returns(new PhysicalFileProvider(Directory.GetCurrentDirectory()));

            var httpContext = new DefaultHttpContext();
            httpContext.Response.Body = new MemoryStream();
            httpContext.RequestServices = new ServiceCollection()
                .AddInstance<IHostingEnvironment>(appEnvironment.Object)
                .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:RehanSaeed,项目名称:Mvc,代码行数:27,代码来源:FilePathResultTest.cs

示例5: ExecuteResultAsync

        public override Task ExecuteResultAsync(ActionContext context)
        {
            var webSocket = context.HttpContext.WebSockets.AcceptWebSocketAsync().Result;

            BlockingStream stream = new BlockingStream(16);

            //Read from stream as it comes in.
            Task.Factory.StartNew(() => _streamHandlerAction(stream));

            var receive = Task.Factory.StartNew(() =>
            {
                byte[] buffer = new byte[1024 * 63];

                while (true)
                {
                    // MUST read if we want the state to get updated...
                    var result = webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None).Result;

                    stream.Write(buffer, 0, result.Count);

                    if (result.MessageType == WebSocketMessageType.Close)
                    {
                        webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, String.Empty, CancellationToken.None);
                        stream.CompleteWriting();
                        break;
                    }
                }

            });
            return receive;
        }
开发者ID:aluitink,项目名称:Ojibwe,代码行数:31,代码来源:MultiBlobPartStreamActionResult.cs

示例6: OnFormatting

        /// <inheritdoc />
        public override void OnFormatting(ActionContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            base.OnFormatting(context);

            var urlHelper = UrlHelper;
            if (urlHelper == null)
            {
                var services = context.HttpContext.RequestServices;
                urlHelper = services.GetRequiredService<IUrlHelperFactory>().GetUrlHelper(context);
            }

            var url = urlHelper.Link(RouteName, RouteValues);

            if (string.IsNullOrEmpty(url))
            {
                throw new InvalidOperationException(Resources.NoRoutesMatched);
            }

            context.HttpContext.Response.Headers[HeaderNames.Location] = url;
        }
开发者ID:phinq19,项目名称:git_example,代码行数:26,代码来源:CreatedAtRouteResult.cs

示例7: ExecuteResultAsync_ReturnsError_IfViewCouldNotBeFound

        public async Task ExecuteResultAsync_ReturnsError_IfViewCouldNotBeFound()
        {
            // Arrange
            var expected = string.Join(Environment.NewLine,
                                       "The view 'MyView' was not found. The following locations were searched:",
                                       "Location1",
                                       "Location2.");
            var actionContext = new ActionContext(GetHttpContext(),
                                                  new RouteData(),
                                                  new ActionDescriptor());
            var viewEngine = new Mock<IViewEngine>();
            viewEngine.Setup(v => v.FindPartialView(It.IsAny<ActionContext>(), It.IsAny<string>()))
                      .Returns(ViewEngineResult.NotFound("MyView", new[] { "Location1", "Location2" }))
                       .Verifiable();

            var viewResult = new PartialViewResult
            {
                ViewEngine = viewEngine.Object,
                ViewName = "MyView"
            };

            // Act and Assert
            var ex = await Assert.ThrowsAsync<InvalidOperationException>(
                                () => viewResult.ExecuteResultAsync(actionContext));
            Assert.Equal(expected, ex.Message);
            viewEngine.Verify();
        }
开发者ID:notami18,项目名称:Mvc,代码行数:27,代码来源:PartialViewResultTest.cs

示例8: ExecuteResultAsync_InvokesForbiddenAsyncOnAllConfiguredSchemes

        public async Task ExecuteResultAsync_InvokesForbiddenAsyncOnAllConfiguredSchemes()
        {
            // Arrange
            var authProperties = new AuthenticationProperties();
            var authenticationManager = new Mock<AuthenticationManager>();
            authenticationManager
                .Setup(c => c.ForbidAsync("Scheme1", authProperties))
                .Returns(TaskCache.CompletedTask)
                .Verifiable();
            authenticationManager
                .Setup(c => c.ForbidAsync("Scheme2", 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 ForbidResult(new[] { "Scheme1", "Scheme2" }, authProperties);
            var routeData = new RouteData();

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

            // Act
            await result.ExecuteResultAsync(actionContext);

            // Assert
            authenticationManager.Verify();
        }
开发者ID:phinq19,项目名称:git_example,代码行数:30,代码来源:ForbidResultTest.cs

示例9: BindActionArgumentsAsync

        public async Task<IDictionary<string, object>> BindActionArgumentsAsync(
            ActionContext actionContext,
            ActionBindingContext actionBindingContext, 
            object controller)
        {
            var actionDescriptor = actionContext.ActionDescriptor as ControllerActionDescriptor;
            if (actionDescriptor == null)
            {
                throw new ArgumentException(
                    Resources.FormatActionDescriptorMustBeBasedOnControllerAction(
                        typeof(ControllerActionDescriptor)),
                        nameof(actionContext));
            }

            var operationBindingContext = GetOperationBindingContext(actionContext, actionBindingContext);
            var controllerProperties = new Dictionary<string, object>(StringComparer.Ordinal);
            await PopulateArgumentsAsync(
                operationBindingContext,
                actionContext.ModelState,
                controllerProperties,
                actionDescriptor.BoundProperties);
            var controllerType = actionDescriptor.ControllerTypeInfo.AsType();
            ActivateProperties(controller, controllerType, controllerProperties);

            var actionArguments = new Dictionary<string, object>(StringComparer.Ordinal);
            await PopulateArgumentsAsync(
                operationBindingContext,
                actionContext.ModelState,
                actionArguments,
                actionDescriptor.Parameters);
            return actionArguments;
        }   
开发者ID:AndersBillLinden,项目名称:Mvc,代码行数:32,代码来源:DefaultControllerActionArgumentBinder.cs

示例10: ExecuteResultAsync

        /// <inheritdoc />
        public override Task ExecuteResultAsync(ActionContext context)
        {
            var response = context.HttpContext.Response;

            response.ContentType = ContentType.Bson;

            if (StatusCode != null)
            {
                response.StatusCode = StatusCode.Value;
            }

            var serializerSettings = _serializerSettings;
            if (serializerSettings == null)
            {
                serializerSettings = context
                    .HttpContext
                    .RequestServices
                    .GetRequiredService<IOptions<MvcJsonOptions>>()
                    .Value
                    .SerializerSettings;
            }

            using (var bsonWriter = new BsonWriter(response.Body))
            {
                bsonWriter.CloseOutput = false;
                var jsonSerializer = JsonSerializer.Create(serializerSettings);
                jsonSerializer.Serialize(bsonWriter, Value);
            }

            return Task.FromResult(true);
        }
开发者ID:netusers2014,项目名称:ASP.NET-MVC-Boilerplate,代码行数:32,代码来源:BsonResult.cs

示例11: ExecuteResult_UsesEncoderIfSpecified

        public async Task ExecuteResult_UsesEncoderIfSpecified()
        {
            // Arrange
            var expected = Enumerable.Concat(Encoding.UTF8.GetPreamble(), _abcdUTF8Bytes);
            var memoryStream = new MemoryStream();
            var response = new Mock<HttpResponse>();
            response.SetupGet(r => r.Body)
                   .Returns(memoryStream);
            var context = new Mock<HttpContext>();
            context.SetupGet(c => c.Response)
                   .Returns(response.Object);
            var actionContext = new ActionContext(context.Object,
                                                  new RouteData(),
                                                  new ActionDescriptor());
            var result = new JsonResult(new { foo = "abcd" })
            {
                Encoding = Encoding.UTF8
            };

            // Act
            await result.ExecuteResultAsync(actionContext);

            // Assert
            Assert.Equal(expected, memoryStream.ToArray());
        }
开发者ID:Nakro,项目名称:Mvc,代码行数:25,代码来源:JsonResultTest.cs

示例12: ExecuteResultAsync

 public override Task ExecuteResultAsync(ActionContext context)
 {
     var executor = context.HttpContext.RequestServices.GetRequiredService<ObjectResultExecutor>();
     var result =  executor.ExecuteAsync(context, this);
     
     return result;
 }
开发者ID:phinq19,项目名称:git_example,代码行数:7,代码来源:ObjectResult.cs

示例13: ObjectResult_ExecuteResultAsync_SetsStatusCode

        public async Task ObjectResult_ExecuteResultAsync_SetsStatusCode()
        {
            // Arrange
            var result = new ObjectResult("Hello")
            {
                StatusCode = 404,
                Formatters = new List<IOutputFormatter>()
                {
                    new NoOpOutputFormatter(),
                },
            };

            var actionContext = new ActionContext()
            {
                HttpContext = new DefaultHttpContext()
                {
                    RequestServices = CreateServices(),
                }
            };

            // Act
            await result.ExecuteResultAsync(actionContext);

            // Assert
            Assert.Equal(404, actionContext.HttpContext.Response.StatusCode);
        }
开发者ID:huoxudong125,项目名称:Mvc,代码行数:26,代码来源:ObjectResultTests.cs

示例14: ExecuteResultAsync

        public async Task ExecuteResultAsync(ActionContext context)
        {
            var routeDef = context.RouteData.DataTokens.ContainsKey("umbraco-route-def")
                ? context.RouteData.DataTokens["umbraco-route-def"] as RouteDefinition
                : null;
            if (routeDef == null)
                throw new InvalidOperationException($"The route data DataTokens must contain an instance of {typeof(RouteDefinition)} with a key of umbraco-route-def");

            var actionFactory = context.HttpContext.RequestServices
                .GetService<IActionInvokerFactory>();
            var providers = context.HttpContext.RequestServices
                .GetService<IActionDescriptorsCollectionProvider>();

            var actionDesc = providers.ActionDescriptors
                .Items
                .OfType<ControllerActionDescriptor>()
                .First(x => x.ControllerName.InvariantEquals(routeDef.ControllerName) && x.Name.InvariantEquals(routeDef.ActionName));

            var copied = new ActionContext(context.HttpContext, context.RouteData, actionDesc);
            copied.ModelState.Merge(context.ModelState);

            copied.RouteData.DataTokens["umbraco-vdd"] = _vdd;

            await actionFactory.CreateInvoker(copied).InvokeAsync();
        }
开发者ID:vnbaaij,项目名称:Umbraco9,代码行数:25,代码来源:ProxyControllerActionResult.cs

示例15: ExecuteResultAsync

        public override Task ExecuteResultAsync(ActionContext context) {
            if(context == null) {
                throw new ArgumentNullException(nameof(context));
            }

            return iCalendarOutputFormatter.WriteResponseBodyAsync(context.HttpContext.Response, _uid, _datetime, _duration, _summary, _description, _location);
        }
开发者ID:migrap,项目名称:Migrap.AspNet.Mvc.Formatters.iCalendar,代码行数:7,代码来源:iCalendarResult.cs


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