• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C# Mvc.ActionContext类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: PartialViewResult_UsesFindPartialViewOnSpecifiedViewEngineToLocateViews

        public async Task PartialViewResult_UsesFindPartialViewOnSpecifiedViewEngineToLocateViews()
        {
            // Arrange
            var viewName = "myview";
            var context = new ActionContext(GetHttpContext(), new RouteData(), new ActionDescriptor());
            var viewEngine = new Mock<IViewEngine>();
            var view = Mock.Of<IView>();

            viewEngine
                .Setup(e => e.FindPartialView(context, "myview"))
                .Returns(ViewEngineResult.Found("myview", view))
                .Verifiable();

            var viewResult = new PartialViewResult
            {
                ViewName = viewName,
                ViewEngine = viewEngine.Object,
                ViewData = new ViewDataDictionary(new EmptyModelMetadataProvider()),
                TempData = Mock.Of<ITempDataDictionary>(),
            };

            // Act
            await viewResult.ExecuteResultAsync(context);

            // Assert
            viewEngine.Verify();
        }
开发者ID:4myBenefits,项目名称:Mvc,代码行数:27,代码来源:PartialViewResultTest.cs


示例17: ExecuteResultAsync

        public override async Task ExecuteResultAsync(ActionContext context)
        {
            // See if the list of content types added to this object result is valid.
            ThrowIfUnsupportedContentType();
            var formatters = GetDefaultFormatters(context);
            var formatterContext = new OutputFormatterContext()
            {
                DeclaredType = DeclaredType,
                ActionContext = context,
                Object = Value,
                StatusCode = StatusCode
            };

            var selectedFormatter = SelectFormatter(formatterContext, formatters);
            if (selectedFormatter == null)
            {
                // No formatter supports this.
                context.HttpContext.Response.StatusCode = StatusCodes.Status406NotAcceptable;
                return;
            }

            if (StatusCode.HasValue)
            {
                context.HttpContext.Response.StatusCode = StatusCode.Value;
            }

            OnFormatting(context);
            await selectedFormatter.WriteAsync(formatterContext);
        }
开发者ID:AndersBillLinden,项目名称:Mvc,代码行数:29,代码来源:ObjectResult.cs


示例18: RedirectToRoute_Execute_PassesCorrectValuesToRedirect

        public async void RedirectToRoute_Execute_PassesCorrectValuesToRedirect(object values)
        {
            // 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 RedirectToRouteResult(null, PropertyHelper.ObjectToDictionary(values))
            {
                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:phinq19,项目名称:git_example,代码行数:31,代码来源:RedirectToRouteResultTest.cs


示例19: GetViewComponentContext

        private static ViewComponentContext GetViewComponentContext(IView view, Stream stream)
        {
            var actionContext = new ActionContext(GetHttpContext(), new RouteData(), new ActionDescriptor());
            var viewData = new ViewDataDictionary(new EmptyModelMetadataProvider());
            var viewContext = new ViewContext(
                actionContext,
                view,
                viewData,
                Mock.Of<ITempDataDictionary>(),
                TextWriter.Null,
                new HtmlHelperOptions());

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

            var viewComponentDescriptor = new ViewComponentDescriptor()
            {
                Type = typeof(object),
            };

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

            return viewComponentContext;
        }
开发者ID:phinq19,项目名称:git_example,代码行数:28,代码来源:JsonViewComponentResultTest.cs


示例20: RedirectToRoute_Execute_ThrowsOnNullUrl

        public async Task RedirectToRoute_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 RedirectToRouteResult(null, new Dictionary<string, object>())
            {
                UrlHelper = urlHelper,
            };

            // Act & Assert
            await ExceptionAssert.ThrowsAsync<InvalidOperationException>(
                async () =>
                {
                    await result.ExecuteResultAsync(actionContext);
                },
                "No route matches the supplied values.");
        }
开发者ID:phinq19,项目名称:git_example,代码行数:27,代码来源:RedirectToRouteResultTest.cs



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# Abstractions.ParameterDescriptor类代码示例发布时间:2022-05-26
下一篇:
C# Test.SimpleDTOWithNestedDTO类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap