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


C# Internal.DefaultHttpContext类代码示例

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


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

示例1: GetIdentifier_ExistingSession_NotNull

        public void GetIdentifier_ExistingSession_NotNull()
        {
            var ctxt = new DefaultHttpContext();
            var session = Subject.Initialize(ctxt);

            Assert.Equal(session, Subject.GetIdentifier(ctxt));
        }
开发者ID:geffzhang,项目名称:Bolt,代码行数:7,代码来源:SessionHandlerTest.cs

示例2: Create_InstanceNotNull

        public async Task Create_InstanceNotNull()
        {
            var ctxt = new DefaultHttpContext();

            var session = await CreateNew(ctxt, "Test");
            Assert.NotNull(session.Instance);
        }
开发者ID:geffzhang,项目名称:Bolt,代码行数:7,代码来源:MemorySessionFactoryTest.cs

示例3: CopyConstructor_CopiesExpectedProperties

        public void CopyConstructor_CopiesExpectedProperties()
        {
            // Arrange
            var httpContext = new DefaultHttpContext();
            var originalContext = new ViewContext(
                new ActionContext(httpContext, new RouteData(), new ActionDescriptor()),
                view: Mock.Of<IView>(),
                viewData: new ViewDataDictionary(metadataProvider: new EmptyModelMetadataProvider()),
                tempData: new TempDataDictionary(httpContext, Mock.Of<ITempDataProvider>()),
                writer: TextWriter.Null,
                htmlHelperOptions: new HtmlHelperOptions());
            var view = Mock.Of<IView>();
            var viewData = new ViewDataDictionary(originalContext.ViewData);
            var writer = new HtmlContentWrapperTextWriter(new HtmlContentBuilder(), Encoding.UTF8);

            // Act
            var context = new ViewContext(originalContext, view, viewData, writer);

            // Assert
            Assert.Same(originalContext.ActionDescriptor, context.ActionDescriptor);
            Assert.Equal(originalContext.ClientValidationEnabled, context.ClientValidationEnabled);
            Assert.Same(originalContext.ExecutingFilePath, context.ExecutingFilePath);
            Assert.Same(originalContext.FormContext, context.FormContext);
            Assert.Equal(originalContext.Html5DateRenderingMode, context.Html5DateRenderingMode);
            Assert.Same(originalContext.HttpContext, context.HttpContext);
            Assert.Same(originalContext.ModelState, context.ModelState);
            Assert.Same(originalContext.RouteData, context.RouteData);
            Assert.Same(originalContext.TempData, context.TempData);
            Assert.Same(originalContext.ValidationMessageElement, context.ValidationMessageElement);
            Assert.Same(originalContext.ValidationSummaryMessageElement, context.ValidationSummaryMessageElement);

            Assert.Same(view, context.View);
            Assert.Same(viewData, context.ViewData);
            Assert.Same(writer, context.Writer);
        }
开发者ID:phinq19,项目名称:git_example,代码行数:35,代码来源:ViewContextTests.cs

示例4: Initialize_SessionHeaderCreated

        public void Initialize_SessionHeaderCreated()
        {
            var ctxt = new DefaultHttpContext();
            var session = Subject.Initialize(ctxt);

            Assert.Equal(session, ctxt.Response.Headers[Options.SessionHeader]);
        }
开发者ID:geffzhang,项目名称:Bolt,代码行数:7,代码来源:SessionHandlerTest.cs

示例5: 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.AddInstance<IHttpContextAccessor>(contextAccessor);

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

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

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

            return contextAccessor;
        }
开发者ID:hackathonvixion,项目名称:ApplicationInsights-aspnet5,代码行数:28,代码来源:HttpContextAccessorHelper.cs

示例6: SettingViewData_AlsoUpdatesViewBag

        public void SettingViewData_AlsoUpdatesViewBag()
        {
            // Arrange
            var httpContext = new DefaultHttpContext();
            var originalViewData = new ViewDataDictionary(metadataProvider: new EmptyModelMetadataProvider());
            var context = new ViewContext(
                new ActionContext(new DefaultHttpContext(), new RouteData(), new ActionDescriptor()),
                view: Mock.Of<IView>(),
                viewData: originalViewData,
                tempData: new TempDataDictionary(httpContext, Mock.Of<ITempDataProvider>()),
                writer: TextWriter.Null,
                htmlHelperOptions: new HtmlHelperOptions());
            var replacementViewData = new ViewDataDictionary(metadataProvider: new EmptyModelMetadataProvider());

            // Act
            context.ViewBag.Hello = "goodbye";
            context.ViewData = replacementViewData;
            context.ViewBag.Another = "property";

            // Assert
            Assert.NotSame(originalViewData, context.ViewData);
            Assert.Same(replacementViewData, context.ViewData);
            Assert.Null(context.ViewBag.Hello);
            Assert.Equal("property", context.ViewBag.Another);
            Assert.Equal("property", context.ViewData["Another"]);
        }
开发者ID:phinq19,项目名称:git_example,代码行数:26,代码来源:ViewContextTests.cs

示例7: Clear_AlreadyStarted_Throws

        public void Clear_AlreadyStarted_Throws()
        {
            var context = new DefaultHttpContext();
            context.Features.Set<IHttpResponseFeature>(new StartedResponseFeature());

            Assert.Throws<InvalidOperationException>(() => context.Response.Clear());
        }
开发者ID:leloulight,项目名称:HttpAbstractions,代码行数:7,代码来源:ResponseExtensionTests.cs

示例8: CanUseRegisterExtensionMethod

        public void CanUseRegisterExtensionMethod()
        {
            var curie = new CuriesLink("aap", "http://www.helpt.com/{?rel}");

            var builder = Hypermedia.CreateBuilder();
            var selfLink = new Link<ProductRepresentation>("product", "http://www.product.com?id=1");
            var link2 = new Link("related", "http://www.related.com");
            var link3 = curie.CreateLink<CategoryRepresentation>("category", "http://www.category.com");

            builder.Register(selfLink, link2, link3);

            var config = builder.Build();

            // arrange
            var mediaFormatter = new JsonHalOutputFormatter(config) { };
            var type = representation.GetType();
            var httpContext = new Mock<HttpContext>();
            var httpRequest = new DefaultHttpContext().Request;
            httpContext.SetupGet(o => o.Request).Returns(httpRequest);

            // act
            using (var stream = new MemoryStream())
            {
                mediaFormatter.WriteResponseBodyAsync(new OutputFormatterWriteContext(httpContext.Object,
                    (s,e)=> new HttpResponseStreamWriter(s, e), type, representation));
                //WriteToStreamAsync(type, representation, stream, content, null);
                stream.Seek(0, SeekOrigin.Begin);
                var serialisedResult = new StreamReader(stream).ReadToEnd();

                // assert
                Approvals.Verify(serialisedResult);
            }
        }
开发者ID:iremezoff,项目名称:AspNet.Hal,代码行数:33,代码来源:HypermediaContainerTests.cs

示例9: 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 = new DefaultHttpContext();
            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:RehanSaeed,项目名称:Mvc,代码行数:32,代码来源:FileStreamResultTest.cs

示例10: WriteFileAsync_CopiesProvidedStream_ToOutputStream

        public async Task WriteFileAsync_CopiesProvidedStream_ToOutputStream()
        {
            // Arrange
            // Generate an array of bytes with a predictable pattern
            // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F, 10, 11, 12, 13
            var originalBytes = Enumerable.Range(0, 0x1234)
                .Select(b => (byte)(b % 20)).ToArray();

            var originalStream = new MemoryStream(originalBytes);

            var httpContext = new DefaultHttpContext();
            var outStream = new MemoryStream();
            httpContext.Response.Body = outStream;

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

            var result = new FileStreamResult(originalStream, "text/plain");

            // Act
            await result.ExecuteResultAsync(actionContext);

            // Assert
            var outBytes = outStream.ToArray();
            Assert.True(originalBytes.SequenceEqual(outBytes));
        }
开发者ID:RehanSaeed,项目名称:Mvc,代码行数:25,代码来源:FileStreamResultTest.cs

示例11: Invoke_DoesNotLog_WhenHandled

        public async void Invoke_DoesNotLog_WhenHandled()
        {
            // Arrange
            var isHandled = true;

            var sink = new TestSink(
                TestSink.EnableWithTypeName<RouterMiddleware>,
                TestSink.EnableWithTypeName<RouterMiddleware>);
            var loggerFactory = new TestLoggerFactory(sink, enabled: true);

            var httpContext = new DefaultHttpContext();
            httpContext.ApplicationServices = new ServiceProvider();
            httpContext.RequestServices = httpContext.ApplicationServices;

            RequestDelegate next = (c) =>
            {
                return Task.FromResult<object>(null);
            };

            var router = new TestRouter(isHandled);
            var middleware = new RouterMiddleware(next, loggerFactory, router);

            // Act
            await middleware.Invoke(httpContext);

            // Assert
            Assert.Empty(sink.Scopes);
            Assert.Empty(sink.Writes);
        }
开发者ID:TerabyteX,项目名称:Routing,代码行数:29,代码来源:RouterMiddlewareTest.cs

示例12: Invoke_LogsCorrectValues_WhenNotHandled

        public async void Invoke_LogsCorrectValues_WhenNotHandled()
        {
            // Arrange
            var expectedMessage = "Request did not match any routes.";
            var isHandled = false;

            var sink = new TestSink(
                TestSink.EnableWithTypeName<RouterMiddleware>,
                TestSink.EnableWithTypeName<RouterMiddleware>);
            var loggerFactory = new TestLoggerFactory(sink, enabled: true);

            var httpContext = new DefaultHttpContext();
            httpContext.ApplicationServices = new ServiceProvider();
            httpContext.RequestServices = httpContext.ApplicationServices;

            RequestDelegate next = (c) =>
            {
                return Task.FromResult<object>(null);
            };

            var router = new TestRouter(isHandled);
            var middleware = new RouterMiddleware(next, loggerFactory, router);

            // Act
            await middleware.Invoke(httpContext);

            // Assert
            Assert.Empty(sink.Scopes);
            Assert.Single(sink.Writes);
            Assert.Equal(expectedMessage, sink.Writes[0].State?.ToString());
        }
开发者ID:TerabyteX,项目名称:Routing,代码行数:31,代码来源:RouterMiddlewareTest.cs

示例13: SelectResponseCharacterEncoding_SelectsEncoding

        public void SelectResponseCharacterEncoding_SelectsEncoding(
            string acceptCharsetHeaders,
            string[] supportedEncodings,
            string expectedEncoding)
        {
            // Arrange
            var httpContext = new Mock<HttpContext>();
            var httpRequest = new DefaultHttpContext().Request;
            httpRequest.Headers[HeaderNames.AcceptCharset] = acceptCharsetHeaders;
            httpRequest.Headers[HeaderNames.Accept] = "application/acceptCharset";
            httpContext.SetupGet(o => o.Request).Returns(httpRequest);

            var formatter = new TestOutputFormatter();
            foreach (string supportedEncoding in supportedEncodings)
            {
                formatter.SupportedEncodings.Add(Encoding.GetEncoding(supportedEncoding));
            }

            var context = new OutputFormatterWriteContext(
                httpContext.Object,
                new TestHttpResponseStreamWriterFactory().CreateWriter,
                typeof(string),
                "someValue")
            {
                ContentType = MediaTypeHeaderValue.Parse(httpRequest.Headers[HeaderNames.Accept]),
            };

            // Act
            var actualEncoding = formatter.SelectCharacterEncoding(context);

            // Assert
            Assert.Equal(Encoding.GetEncoding(expectedEncoding), actualEncoding);
        }
开发者ID:huoxudong125,项目名称:Mvc,代码行数:33,代码来源:OutputFormatterTests.cs

示例14: GetViewComponentContext

        private static ViewComponentContext GetViewComponentContext(IView view, Stream stream)
        {
            var httpContext = new DefaultHttpContext();
            var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor());
            var viewData = new ViewDataDictionary(new EmptyModelMetadataProvider());
            var viewContext = new ViewContext(
                actionContext,
                view,
                viewData,
                new TempDataDictionary(httpContext, new SessionStateTempDataProvider()),
                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,代码行数:29,代码来源:ContentViewComponentResultTest.cs

示例15: ReadFormAsync_SimpleData_ReturnsParsedFormCollection

        public async Task ReadFormAsync_SimpleData_ReturnsParsedFormCollection()
        {
            // Arrange
            var formContent = Encoding.UTF8.GetBytes("foo=bar&baz=2");
            var context = new DefaultHttpContext();
            context.Request.ContentType = "application/x-www-form-urlencoded; charset=utf-8";
            context.Request.Body = new MemoryStream(formContent);

            // Not cached yet
            var formFeature = context.Features.Get<IFormFeature>();
            Assert.Null(formFeature);

            // Act
            var formCollection = await context.Request.ReadFormAsync();

            // Assert
            Assert.Equal("bar", formCollection["foo"]);
            Assert.Equal("2", formCollection["baz"]);
            Assert.Equal(0, context.Request.Body.Position);
            Assert.True(context.Request.Body.CanSeek);

            // Cached
            formFeature = context.Features.Get<IFormFeature>();
            Assert.NotNull(formFeature);
            Assert.NotNull(formFeature.Form);
            Assert.Same(formFeature.Form, formCollection);
        }
开发者ID:leloulight,项目名称:HttpAbstractions,代码行数:27,代码来源:FormFeatureTests.cs


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