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


C# DefaultHttpContext.SetFeature方法代码示例

本文整理汇总了C#中Microsoft.AspNet.Http.Internal.DefaultHttpContext.SetFeature方法的典型用法代码示例。如果您正苦于以下问题:C# DefaultHttpContext.SetFeature方法的具体用法?C# DefaultHttpContext.SetFeature怎么用?C# DefaultHttpContext.SetFeature使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Microsoft.AspNet.Http.Internal.DefaultHttpContext的用法示例。


在下文中一共展示了DefaultHttpContext.SetFeature方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Index_ReturnsNoCartItems_WhenNoItemsInCart

        public async Task Index_ReturnsNoCartItems_WhenNoItemsInCart()
        {
            // Arrange
            var sessionFeature = new SessionFeature()
            {
                Session = CreateTestSession(),
            };

            var httpContext = new DefaultHttpContext();
            httpContext.SetFeature<ISessionFeature>(sessionFeature);
            httpContext.Session.SetString("Session", "CartId_A");

            var controller = new ShoppingCartController()
            {
                DbContext = _serviceProvider.GetRequiredService<MusicStoreContext>(),
            };
            controller.ActionContext.HttpContext = httpContext;

            // Act
            var result = await controller.Index();

            // Assert
            var viewResult = Assert.IsType<ViewResult>(result);
            Assert.NotNull(viewResult.ViewData);
            Assert.Null(viewResult.ViewName);

            var model = Assert.IsType<ShoppingCartViewModel>(viewResult.ViewData.Model);
            Assert.Equal(0, model.CartItems.Count);
            Assert.Equal(0, model.CartTotal);
        }
开发者ID:joerter,项目名称:MusicStore,代码行数:30,代码来源:ShoppingCartControllerTest.cs

示例2: SendFileSupport

 public void SendFileSupport()
 {
     var context = new DefaultHttpContext();
     var response = context.Response;
     Assert.False(response.SupportsSendFile());
     context.SetFeature<IHttpSendFileFeature>(new FakeSendFileFeature());
     Assert.True(response.SupportsSendFile());
 }
开发者ID:Kagamine,项目名称:HttpAbstractions,代码行数:8,代码来源:SendFileResponseExtensionsTests.cs

示例3: AddressAndPayment_RedirectToCompleteWhenSuccessful

        public async Task AddressAndPayment_RedirectToCompleteWhenSuccessful()
        {
            // Arrange
            var httpContext = new DefaultHttpContext();

            var orderId = 10;
            var order = new Order()
            {
                OrderId = orderId,
            };

            // Session initialization
            var cartId = "CartId_A";
            var sessionFeature = new SessionFeature()
            {
                Session = CreateTestSession(),
            };
            httpContext.SetFeature<ISessionFeature>(sessionFeature);
            httpContext.Session.SetString("Session", cartId);

            // FormCollection initialization
            httpContext.Request.Form =
                new FormCollection(
                    new Dictionary<string, string[]>()
                        { { "PromoCode", new string[] { "FREE" } } }
                    );

            // UserName initialization
            var claims = new List<Claim> { new Claim(ClaimTypes.Name, "TestUserName") };
            httpContext.User = new ClaimsPrincipal(new ClaimsIdentity(claims));
            
            // DbContext initialization
            var dbContext = _serviceProvider.GetRequiredService<MusicStoreContext>();
            var cartItems = CreateTestCartItems(
                cartId,
                itemPrice: 10,
                numberOfItem: 1);
            dbContext.AddRange(cartItems.Select(n => n.Album).Distinct());
            dbContext.AddRange(cartItems);
            dbContext.SaveChanges();

            var controller = new CheckoutController()
            {
                DbContext = dbContext,
            };
            controller.ActionContext.HttpContext = httpContext;
            
            // Act
            var result = await controller.AddressAndPayment(order, CancellationToken.None);

            // Assert
            var redirectResult = Assert.IsType<RedirectToActionResult>(result);
            Assert.Equal("Complete", redirectResult.ActionName);
            Assert.Null(redirectResult.ControllerName);
            Assert.NotNull(redirectResult.RouteValues);

            Assert.Equal(orderId, redirectResult.RouteValues["Id"]);
        }
开发者ID:joerter,项目名称:MusicStore,代码行数:58,代码来源:CheckoutControllerTest.cs

示例4: SendFileWorks

        public async Task SendFileWorks()
        {
            var context = new DefaultHttpContext();
            var response = context.Response;
            var fakeFeature = new FakeSendFileFeature();
            context.SetFeature<IHttpSendFileFeature>(fakeFeature);

            await response.SendFileAsync("bob", 1, 3, CancellationToken.None);

            Assert.Equal("bob", fakeFeature.name);
            Assert.Equal(1, fakeFeature.offset);
            Assert.Equal(3, fakeFeature.length);
            Assert.Equal(CancellationToken.None, fakeFeature.token);
        }
开发者ID:Kagamine,项目名称:HttpAbstractions,代码行数:14,代码来源:SendFileResponseExtensionsTests.cs

示例5: GetOnSessionProperty_ReturnsAvailableSession

        public void GetOnSessionProperty_ReturnsAvailableSession()
        {
            // Arrange
            var context = new DefaultHttpContext();
            var session = new TestSession();
            session.Set("key1", null);
            session.Set("key2", null);
            var feature = new BlahSessionFeature();
            feature.Session = session;
            context.SetFeature<ISessionFeature>(feature);

            // Act & Assert
            Assert.Same(session, context.Session);
            context.Session.Set("key3", null);
            Assert.Equal(3, context.Session.Keys.Count());
        }
开发者ID:Kagamine,项目名称:HttpAbstractions,代码行数:16,代码来源:DefaultHttpContextTests.cs

示例6: GetCartId_ReturnsCartIdFromCookies

        public void GetCartId_ReturnsCartIdFromCookies()
        {
            // Arrange
            var cartId = "cartId_A";

            var httpContext = new DefaultHttpContext();
            httpContext.SetFeature<IRequestCookiesFeature>(new CookiesFeature("Session", cartId));

            var cart = new ShoppingCart(new MusicStoreContext());

            // Act
            var result = cart.GetCartId(httpContext);

            // Assert
            Assert.NotNull(result);
            Assert.Equal(cartId, result);
        }
开发者ID:sarasko,项目名称:MusicStore,代码行数:17,代码来源:ShoppingCartTest.cs

示例7: SettingSession_OverridesAvailableSession

        public void SettingSession_OverridesAvailableSession()
        {
            // Arrange
            var context = new DefaultHttpContext();
            var session = new TestSession();
            session.Set("key1", null);
            session.Set("key2", null);
            var feature = new BlahSessionFeature();
            feature.Session = session;
            context.SetFeature<ISessionFeature>(feature);

            // Act
            context.Session = new TestSession();

            // Assert
            Assert.NotSame(session, context.Session);
            Assert.Empty(context.Session.Keys);
        }
开发者ID:Kagamine,项目名称:HttpAbstractions,代码行数:18,代码来源:DefaultHttpContextTests.cs

示例8: ManageControllerTest

        public ManageControllerTest()
        {
            var services = new ServiceCollection();
            services.AddEntityFramework()
                    .AddInMemoryDatabase()
                    .AddDbContext<MusicStoreContext>(options => options.UseInMemoryDatabase());

            services.AddIdentity<ApplicationUser, IdentityRole>()
                    .AddEntityFrameworkStores<MusicStoreContext>();

            services.AddLogging();

            // IHttpContextAccessor is required for SignInManager, and UserManager
            var context = new DefaultHttpContext();
            context.SetFeature<IHttpAuthenticationFeature>(new HttpAuthenticationFeature() { Handler = new TestAuthHandler() });
            services.AddInstance<IHttpContextAccessor>(
                new HttpContextAccessor()
                    {
                        HttpContext = context,
                    });

            _serviceProvider = services.BuildServiceProvider();
        }
开发者ID:renattomachado,项目名称:MusicStore,代码行数:23,代码来源:ManageControllerTest.cs

示例9: ExecuteResultAsync_CallsSendFileAsync_IfIHttpSendFilePresent

        public async Task ExecuteResultAsync_CallsSendFileAsync_IfIHttpSendFilePresent()
        {
            // Arrange
            var path = Path.GetFullPath(Path.Combine("TestFiles", "FilePathResultTestFile.txt"));

            var result = new FilePathResult(path, "text/plain")
            {
                FileProvider = new PhysicalFileProvider(Path.GetFullPath(".")),
            };

            var sendFileMock = new Mock<IHttpSendFileFeature>();
            sendFileMock
                .Setup(s => s.SendFileAsync(path, 0, null, CancellationToken.None))
                .Returns(Task.FromResult<int>(0));

            var httpContext = new DefaultHttpContext();
            httpContext.SetFeature(sendFileMock.Object);

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

            // Act
            await result.ExecuteResultAsync(context);

            // Assert
            sendFileMock.Verify();
        }
开发者ID:RehanSaeed,项目名称:Mvc,代码行数:26,代码来源:FilePathResultTest.cs

示例10: RemoveFromCart_RemovesItemFromCart

        public async Task RemoveFromCart_RemovesItemFromCart()
        {
            // Arrange
            var cartId = "CartId_A";
            var cartItemId = 3;
            var numberOfItem = 5;
            var unitPrice = 10;
            var httpContext = new DefaultHttpContext();

            // Session and cart initialization
            httpContext.Session = new TestSession();
            httpContext.Session.SetString("Session", cartId);

            // DbContext initialization
            var dbContext = _serviceProvider.GetRequiredService<MusicStoreContext>();
            var cartItems = CreateTestCartItems(cartId, unitPrice, numberOfItem);
            dbContext.AddRange(cartItems.Select(n => n.Album).Distinct());
            dbContext.AddRange(cartItems);
            dbContext.SaveChanges();

            // ServiceProvder initialization
            var serviceProviderFeature = new ServiceProvidersFeature();
            httpContext.SetFeature<IServiceProvidersFeature>(serviceProviderFeature);

            // AntiForgery initialization
            serviceProviderFeature.RequestServices = _serviceProvider;
            var antiForgery = serviceProviderFeature.RequestServices.GetRequiredService<IAntiforgery>();
            var tokens = antiForgery.GetTokens(httpContext);

            // Header initialization for AntiForgery
            var headers = new KeyValuePair<string, string[]>(
                "RequestVerificationToken",
                new string[] { tokens.CookieToken + ":" + tokens.FormToken });
            httpContext.Request.Headers.Add(headers);

            // Cotroller initialization
            var controller = new ShoppingCartController()
            {
                DbContext = dbContext,
                Antiforgery = antiForgery,
            };
            controller.ActionContext.HttpContext = httpContext;

            // Act
            var result = await controller.RemoveFromCart(cartItemId, CancellationToken.None);

            // Assert
            var jsonResult = Assert.IsType<JsonResult>(result);
            var viewModel = Assert.IsType<ShoppingCartRemoveViewModel>(jsonResult.Value);
            Assert.Equal(numberOfItem - 1, viewModel.CartCount);
            Assert.Equal((numberOfItem - 1) * 10, viewModel.CartTotal);
            Assert.Equal(" has been removed from your shopping cart.", viewModel.Message);

            var cart = ShoppingCart.GetCart(dbContext, httpContext);
            Assert.False((await cart.GetCartItems()).Any(c => c.CartItemId == cartItemId));
        }
开发者ID:renattomachado,项目名称:MusicStore,代码行数:56,代码来源:ShoppingCartControllerTest.cs

示例11: RequestState

            internal RequestState(HttpRequestMessage request, PathString pathBase, CancellationToken cancellationToken)
            {
                _request = request;
                _responseTcs = new TaskCompletionSource<HttpResponseMessage>();

                if (request.RequestUri.IsDefaultPort)
                {
                    request.Headers.Host = request.RequestUri.Host;
                }
                else
                {
                    request.Headers.Host = request.RequestUri.GetComponents(UriComponents.HostAndPort, UriFormat.UriEscaped);
                }

                FeatureCollection = new FeatureCollection();
                HttpContext = new DefaultHttpContext(FeatureCollection);
                HttpContext.SetFeature<IHttpRequestFeature>(new RequestFeature());
                _responseFeature = new ResponseFeature();
                HttpContext.SetFeature<IHttpResponseFeature>(_responseFeature);
                var serverRequest = HttpContext.Request;
                serverRequest.Protocol = "HTTP/" + request.Version.ToString(2);
                serverRequest.Scheme = request.RequestUri.Scheme;
                serverRequest.Method = request.Method.ToString();

                var fullPath = PathString.FromUriComponent(request.RequestUri);
                PathString remainder;
                if (fullPath.StartsWithSegments(pathBase, out remainder))
                {
                    serverRequest.PathBase = pathBase;
                    serverRequest.Path = remainder;
                }
                else
                {
                    serverRequest.PathBase = PathString.Empty;
                    serverRequest.Path = fullPath;
                }

                serverRequest.QueryString = QueryString.FromUriComponent(request.RequestUri);
                // TODO: serverRequest.CallCancelled = cancellationToken;

                foreach (var header in request.Headers)
                {
                    serverRequest.Headers.AppendValues(header.Key, header.Value.ToArray());
                }
                var requestContent = request.Content;
                if (requestContent != null)
                {
                    foreach (var header in request.Content.Headers)
                    {
                        serverRequest.Headers.AppendValues(header.Key, header.Value.ToArray());
                    }
                }

                _responseStream = new ResponseStream(CompleteResponse);
                HttpContext.Response.Body = _responseStream;
                HttpContext.Response.StatusCode = 200;
            }
开发者ID:humblelistener,项目名称:Hosting,代码行数:57,代码来源:ClientHandler.cs

示例12: GetHttpContext

 private HttpContext GetHttpContext(ISession session, bool sessionEnabled = true)
 {
     var httpContext = new DefaultHttpContext();
     if(sessionEnabled)
     {
         httpContext.SetFeature<ISessionFeature>(new SessionFeature() { Session = session });
     }
     return httpContext;
 }
开发者ID:notami18,项目名称:Mvc,代码行数:9,代码来源:SessionStateTempDataProviderTest.cs

示例13: AddToCart_AddsItemToCart

        public async Task AddToCart_AddsItemToCart()
        {
            // Arrange
            var albumId = 3;
            var sessionFeature = new SessionFeature()
            {
                Session = CreateTestSession(),
            };

            var httpContext = new DefaultHttpContext();
            httpContext.SetFeature<ISessionFeature>(sessionFeature);
            httpContext.Session.SetString("Session", "CartId_A");

            // Creates the albums of AlbumId = 1 ~ 10.
            var dbContext = _serviceProvider.GetRequiredService<MusicStoreContext>();
            var albums = CreateTestAlbums(itemPrice: 10);
            dbContext.AddRange(albums);
            dbContext.SaveChanges();

            var controller = new ShoppingCartController()
            {
                DbContext = dbContext
            };
            controller.ActionContext.HttpContext = httpContext;

            // Act
            var result = await controller.AddToCart(albumId, CancellationToken.None);

            // Assert
            var cart = ShoppingCart.GetCart(dbContext, httpContext);
            Assert.Equal(1, (await cart.GetCartItems()).Count);
            Assert.Equal(albumId, (await cart.GetCartItems()).Single().AlbumId);

            var redirectResult = Assert.IsType<RedirectToActionResult>(result);
            Assert.Null(redirectResult.ControllerName);
            Assert.Equal("Index", redirectResult.ActionName);
        }
开发者ID:joerter,项目名称:MusicStore,代码行数:37,代码来源:ShoppingCartControllerTest.cs

示例14: Index_ReturnsCartItems_WhenItemsInCart

        public async Task Index_ReturnsCartItems_WhenItemsInCart()
        {
            // Arrange
            var cartId = "CartId_A";
            var sessionFeature = new SessionFeature()
            {
                Session = CreateTestSession(),
            };

            var httpContext = new DefaultHttpContext();
            httpContext.SetFeature<ISessionFeature>(sessionFeature);
            httpContext.Session.SetString("Session", cartId);

            var dbContext = _serviceProvider.GetRequiredService<MusicStoreContext>();
            var cartItems = CreateTestCartItems(
                cartId,
                itemPrice: 10,
                numberOfItem: 5);
            dbContext.AddRange(cartItems.Select(n => n.Album).Distinct());
            dbContext.AddRange(cartItems);
            dbContext.SaveChanges();

            var controller = new ShoppingCartController()
            {
                DbContext = dbContext,
            };
            controller.ActionContext.HttpContext = httpContext;

            // Act
            var result = await controller.Index();

            // Assert
            var viewResult = Assert.IsType<ViewResult>(result);
            Assert.NotNull(viewResult.ViewData);
            Assert.Null(viewResult.ViewName);

            var model = Assert.IsType<ShoppingCartViewModel>(viewResult.ViewData.Model);
            Assert.Equal(5, model.CartItems.Count);
            Assert.Equal(5 * 10, model.CartTotal);
        }
开发者ID:joerter,项目名称:MusicStore,代码行数:40,代码来源:ShoppingCartControllerTest.cs


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