本文整理汇总了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));
}
示例2: Create_InstanceNotNull
public async Task Create_InstanceNotNull()
{
var ctxt = new DefaultHttpContext();
var session = await CreateNew(ctxt, "Test");
Assert.NotNull(session.Instance);
}
示例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);
}
示例4: Initialize_SessionHeaderCreated
public void Initialize_SessionHeaderCreated()
{
var ctxt = new DefaultHttpContext();
var session = Subject.Initialize(ctxt);
Assert.Equal(session, ctxt.Response.Headers[Options.SessionHeader]);
}
示例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;
}
示例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"]);
}
示例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());
}
示例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);
}
}
示例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();
}
示例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));
}
示例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);
}
示例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());
}
示例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);
}
示例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;
}
示例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);
}