本文整理汇总了C#中Microsoft.AspNetCore.Http.DefaultHttpContext类的典型用法代码示例。如果您正苦于以下问题:C# DefaultHttpContext类的具体用法?C# DefaultHttpContext怎么用?C# DefaultHttpContext使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
DefaultHttpContext类属于Microsoft.AspNetCore.Http命名空间,在下文中一共展示了DefaultHttpContext类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。
示例1: 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.AddSingleton<IHttpContextAccessor>(contextAccessor);
if (actionContext != null)
{
var si = new ActionContextAccessor();
si.ActionContext = actionContext;
services.AddSingleton<IActionContextAccessor>(si);
}
if (requestTelemetry != null)
{
services.AddSingleton<RequestTelemetry>(requestTelemetry);
}
IServiceProvider serviceProvider = services.BuildServiceProvider();
contextAccessor.HttpContext.RequestServices = serviceProvider;
return contextAccessor;
}
开发者ID:RehanSaeed,项目名称:ApplicationInsights-aspnetcore,代码行数:28,代码来源:HttpContextAccessorHelper.cs
示例2: 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.RequestServices = new ServiceProvider();
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:Corays,项目名称:Routing,代码行数:28,代码来源:RouterMiddlewareTest.cs
示例3: 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:cemalshukriev,项目名称:Mvc,代码行数:26,代码来源:ViewContextTests.cs
示例4: 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 StringWriter();
// 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:cemalshukriev,项目名称:Mvc,代码行数:35,代码来源:ViewContextTests.cs
示例5: CreateResponse_DoingConneg_OnlyContent_RetrievesContentNegotiatorFromServices
public void CreateResponse_DoingConneg_OnlyContent_RetrievesContentNegotiatorFromServices()
{
// Arrange
var context = new DefaultHttpContext();
var services = new Mock<IServiceProvider>();
services
.Setup(s => s.GetService(typeof(IContentNegotiator)))
.Returns(Mock.Of<IContentNegotiator>())
.Verifiable();
var options = new WebApiCompatShimOptions();
options.Formatters.AddRange(new MediaTypeFormatterCollection());
var optionsAccessor = new Mock<IOptions<WebApiCompatShimOptions>>();
optionsAccessor.SetupGet(o => o.Value).Returns(options);
services
.Setup(s => s.GetService(typeof(IOptions<WebApiCompatShimOptions>)))
.Returns(optionsAccessor.Object);
context.RequestServices = services.Object;
var request = CreateRequest(context);
// Act
request.CreateResponse(CreateValue());
// Assert
services.Verify();
}
开发者ID:cemalshukriev,项目名称:Mvc,代码行数:31,代码来源:HttpRequestMessageExtensionsTest.cs
示例6: GenerateRequestToken_AuthenticatedWithoutUsernameAndNoAdditionalData_NoAdditionalData
public void GenerateRequestToken_AuthenticatedWithoutUsernameAndNoAdditionalData_NoAdditionalData()
{
// Arrange
var cookieToken = new AntiforgeryToken()
{
IsCookieToken = true
};
var httpContext = new DefaultHttpContext();
httpContext.User = new ClaimsPrincipal(new MyAuthenticatedIdentityWithoutUsername());
var options = new AntiforgeryOptions();
var claimUidExtractor = new Mock<IClaimUidExtractor>().Object;
var tokenProvider = new DefaultAntiforgeryTokenGenerator(
claimUidExtractor: claimUidExtractor,
additionalDataProvider: null);
// Act & assert
var exception = Assert.Throws<InvalidOperationException>(
() => tokenProvider.GenerateRequestToken(httpContext, cookieToken));
Assert.Equal(
"The provided identity of type " +
$"'{typeof(MyAuthenticatedIdentityWithoutUsername).FullName}' " +
"is marked IsAuthenticated = true but does not have a value for Name. " +
"By default, the antiforgery system requires that all authenticated identities have a unique Name. " +
"If it is not possible to provide a unique Name for this identity, " +
"consider extending IAntiforgeryAdditionalDataProvider by overriding the " +
"DefaultAntiforgeryAdditionalDataProvider " +
"or a custom type that can provide some form of unique identifier for the current user.",
exception.Message);
}
开发者ID:ciwchris,项目名称:Antiforgery,代码行数:32,代码来源:DefaultAntiforgeryTokenGeneratorTest.cs
示例7: OnActionExecuted_HandlesExceptionAndReturnsObjectResult
public void OnActionExecuted_HandlesExceptionAndReturnsObjectResult()
{
// Arrange
var filter = new HttpResponseExceptionActionFilter();
var httpContext = new DefaultHttpContext();
httpContext.Request.Method = "GET";
var actionContext = new ActionContext(
httpContext,
new RouteData(),
Mock.Of<ActionDescriptor>());
var context = new ActionExecutedContext(
actionContext,
filters: new List<IFilterMetadata>(),
controller: new object());
context.Exception = new HttpResponseException(HttpStatusCode.BadRequest);
// Act
filter.OnActionExecuted(context);
// Assert
Assert.True(context.ExceptionHandled);
var result = Assert.IsType<ObjectResult>(context.Result);
Assert.Equal(typeof(HttpResponseMessage), result.DeclaredType);
var response = Assert.IsType<HttpResponseMessage>(result.Value);
Assert.NotNull(response.RequestMessage);
Assert.Equal(context.HttpContext.GetHttpRequestMessage(), response.RequestMessage);
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
}
开发者ID:ymd1223,项目名称:Mvc,代码行数:31,代码来源:HttpResponseExceptionActionFilterTest.cs
示例8: ManageControllerTest
public ManageControllerTest()
{
var efServiceProvider = new ServiceCollection().AddEntityFrameworkInMemoryDatabase().BuildServiceProvider();
var services = new ServiceCollection();
services.AddOptions();
services
.AddDbContext<MusicStoreContext>(b => b.UseInMemoryDatabase().UseInternalServiceProvider(efServiceProvider));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<MusicStoreContext>();
services.AddLogging();
services.AddOptions();
// IHttpContextAccessor is required for SignInManager, and UserManager
var context = new DefaultHttpContext();
context.Features.Set<IHttpAuthenticationFeature>(new HttpAuthenticationFeature() { Handler = new TestAuthHandler() });
services.AddSingleton<IHttpContextAccessor>(
new HttpContextAccessor()
{
HttpContext = context,
});
_serviceProvider = services.BuildServiceProvider();
}
开发者ID:Cream2015,项目名称:MusicStore,代码行数:26,代码来源:ManageControllerTest.cs
示例9: 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()
{
TypeInfo = typeof(object).GetTypeInfo(),
};
var viewComponentContext = new ViewComponentContext(
viewComponentDescriptor,
new Dictionary<string, object>(),
new HtmlTestEncoder(),
viewContext,
writer);
return viewComponentContext;
}
开发者ID:ymd1223,项目名称:Mvc,代码行数:29,代码来源:ContentViewComponentResultTest.cs
示例10: InvalidModelStateResult_WritesHttpError
public async Task InvalidModelStateResult_WritesHttpError()
{
// Arrange
var httpContext = new DefaultHttpContext();
httpContext.RequestServices = CreateServices();
var stream = new MemoryStream();
httpContext.Response.Body = stream;
var context = new ActionContext(httpContext, new RouteData(), new ActionDescriptor());
var modelState = new ModelStateDictionary();
modelState.AddModelError("product.Name", "Name is required.");
var expected =
"{\"Message\":\"The request is invalid.\"," +
"\"ModelState\":{\"product.Name\":[\"Name is required.\"]}}";
var result = new InvalidModelStateResult(modelState, includeErrorDetail: false);
// Act
await result.ExecuteResultAsync(context);
// Assert
using (var reader = new StreamReader(stream))
{
stream.Seek(0, SeekOrigin.Begin);
var content = reader.ReadToEnd();
Assert.Equal(expected, content);
}
}
开发者ID:cemalshukriev,项目名称:Mvc,代码行数:31,代码来源:InvalidModelStateResultTest.cs
示例11: 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 = new StringSegment(httpRequest.Headers[HeaderNames.Accept]),
};
// Act
var actualEncoding = formatter.SelectCharacterEncoding(context);
// Assert
Assert.Equal(Encoding.GetEncoding(expectedEncoding), actualEncoding);
}
开发者ID:cemalshukriev,项目名称:Mvc,代码行数:33,代码来源:TextOutputFormatterTests.cs
示例12: Create_TypeActivatesTypesWithServices
public void Create_TypeActivatesTypesWithServices()
{
// Arrange
var activator = new DefaultControllerActivator(new TypeActivatorCache());
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 context = new ControllerContext(
new ActionContext(
httpContext,
new RouteData(),
new ControllerActionDescriptor
{
ControllerTypeInfo = typeof(TypeDerivingFromControllerWithServices).GetTypeInfo()
}));
// Act
var instance = activator.Create(context);
// Assert
var controller = Assert.IsType<TypeDerivingFromControllerWithServices>(instance);
Assert.Same(testService, controller.TestService);
serviceProvider.Verify();
}
开发者ID:ymd1223,项目名称:Mvc,代码行数:32,代码来源:DefaultControllerActivatorTest.cs
示例13: Create_CreatesInstancesOfTypes
public void Create_CreatesInstancesOfTypes(Type type)
{
// Arrange
var activator = new DefaultControllerActivator(new TypeActivatorCache());
var serviceProvider = new Mock<IServiceProvider>(MockBehavior.Strict);
var httpContext = new DefaultHttpContext
{
RequestServices = serviceProvider.Object
};
var context = new ControllerContext(
new ActionContext(
httpContext,
new RouteData(),
new ControllerActionDescriptor
{
ControllerTypeInfo = type.GetTypeInfo()
}));
// Act
var instance = activator.Create(context);
// Assert
Assert.IsType(type, instance);
}
开发者ID:ymd1223,项目名称:Mvc,代码行数:26,代码来源:DefaultControllerActivatorTest.cs
示例14: Create_ThrowsIfControllerIsNotRegisteredInServiceProvider
public void Create_ThrowsIfControllerIsNotRegisteredInServiceProvider()
{
// Arrange
var expected = "No service for type '" + typeof(DIController) + "' has been registered.";
var controller = new DIController();
var httpContext = new DefaultHttpContext
{
RequestServices = Mock.Of<IServiceProvider>()
};
var activator = new ServiceBasedControllerActivator();
var context = new ControllerContext(
new ActionContext(
httpContext,
new RouteData(),
new ControllerActionDescriptor
{
ControllerTypeInfo = typeof(DIController).GetTypeInfo()
}));
// Act and Assert
var ex = Assert.Throws<InvalidOperationException>(
() => activator.Create(context));
Assert.Equal(expected, ex.Message);
}
开发者ID:cemalshukriev,项目名称:Mvc,代码行数:27,代码来源:ServiceBasedControllerActivatorTest.cs
示例15: TestBase
public TestBase()
{
if (ServiceProvider == null)
{
var services = new ServiceCollection();
// set up empty in-memory test db
services
.AddEntityFrameworkInMemoryDatabase()
.AddDbContext<AllReadyContext>(options => options.UseInMemoryDatabase().UseInternalServiceProvider(services.BuildServiceProvider()));
// add identity service
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<AllReadyContext>();
var context = new DefaultHttpContext();
context.Features.Set<IHttpAuthenticationFeature>(new HttpAuthenticationFeature());
services.AddSingleton<IHttpContextAccessor>(h => new HttpContextAccessor { HttpContext = context });
// Setup hosting environment
IHostingEnvironment hostingEnvironment = new HostingEnvironment();
hostingEnvironment.EnvironmentName = "Development";
services.AddSingleton(x => hostingEnvironment);
// set up service provider for tests
ServiceProvider = services.BuildServiceProvider();
}
}
开发者ID:gftrader,项目名称:allReady,代码行数:27,代码来源:TestBase.cs
示例16: 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.RequestServices = new ServiceProvider();
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:Corays,项目名称:Routing,代码行数:30,代码来源:RouterMiddlewareTest.cs
示例17: Create_GetsServicesFromServiceProvider
public void Create_GetsServicesFromServiceProvider()
{
// Arrange
var controller = new DIController();
var serviceProvider = new Mock<IServiceProvider>(MockBehavior.Strict);
serviceProvider.Setup(s => s.GetService(typeof(DIController)))
.Returns(controller)
.Verifiable();
var httpContext = new DefaultHttpContext
{
RequestServices = serviceProvider.Object
};
var activator = new ServiceBasedControllerActivator();
var context = new ControllerContext(new ActionContext(
httpContext,
new RouteData(),
new ControllerActionDescriptor
{
ControllerTypeInfo = typeof(DIController).GetTypeInfo()
}));
// Act
var instance = activator.Create(context);
// Assert
Assert.Same(controller, instance);
serviceProvider.Verify();
}
开发者ID:cemalshukriev,项目名称:Mvc,代码行数:28,代码来源:ServiceBasedControllerActivatorTest.cs
示例18: EmptyContext
public async void EmptyContext()
{
var context = new DefaultHttpContext();
var secret = await _parser.ParseAsync(context);
secret.Should().BeNull();
}
开发者ID:RajMondaz,项目名称:IdentityServer4,代码行数:8,代码来源:BasicAuthenticationCredentialParsing.cs
示例19: GetHttpContext
private static HttpContext GetHttpContext()
{
var httpContext = new DefaultHttpContext();
httpContext.Request.PathBase = new PathString("");
httpContext.Response.Body = new MemoryStream();
httpContext.RequestServices = CreateServices();
return httpContext;
}
开发者ID:xuchrist,项目名称:Mvc,代码行数:8,代码来源:HttpNotFoundObjectResultTest.cs
示例20: WithHttpContextShouldPopulateCustomHttpContextForPocoController
public void WithHttpContextShouldPopulateCustomHttpContextForPocoController()
{
MyApplication
.StartsFrom<TestStartup>()
.WithServices(services =>
{
services.AddMemoryCache();
services.AddDistributedMemoryCache();
services.AddSession();
services.AddHttpContextAccessor();
});
var httpContext = new DefaultHttpContext();
httpContext.Request.Scheme = "Custom";
httpContext.Response.StatusCode = 404;
httpContext.Response.ContentType = ContentType.ApplicationJson;
httpContext.Response.ContentLength = 100;
MyController<MvcController>
.Instance()
.WithHttpContext(httpContext)
.ShouldPassForThe<HttpContext>(setHttpContext =>
{
Assert.Equal("Custom", setHttpContext.Request.Scheme);
Assert.IsAssignableFrom<HttpResponseMock>(setHttpContext.Response);
Assert.Same(httpContext.Response.Body, setHttpContext.Response.Body);
Assert.Equal(httpContext.Response.ContentLength, setHttpContext.Response.ContentLength);
Assert.Equal(httpContext.Response.ContentType, setHttpContext.Response.ContentType);
Assert.Equal(httpContext.Response.StatusCode, setHttpContext.Response.StatusCode);
Assert.Same(httpContext.Items, setHttpContext.Items);
Assert.Same(httpContext.Features, setHttpContext.Features);
Assert.Same(httpContext.RequestServices, setHttpContext.RequestServices);
Assert.Same(httpContext.Session, setHttpContext.Session);
Assert.Same(httpContext.TraceIdentifier, setHttpContext.TraceIdentifier);
Assert.Same(httpContext.User, setHttpContext.User);
});
MyController<PocoController>
.Instance()
.WithHttpContext(httpContext)
.ShouldPassForThe<PocoController>(controller =>
{
Assert.Equal("Custom", controller.CustomHttpContext.Request.Scheme);
Assert.IsAssignableFrom<HttpResponseMock>(controller.CustomHttpContext.Response);
Assert.Same(httpContext.Response.Body, controller.CustomHttpContext.Response.Body);
Assert.Equal(httpContext.Response.ContentLength, controller.CustomHttpContext.Response.ContentLength);
Assert.Equal(httpContext.Response.ContentType, controller.CustomHttpContext.Response.ContentType);
Assert.Equal(httpContext.Response.StatusCode, controller.CustomHttpContext.Response.StatusCode);
Assert.Same(httpContext.Items, controller.CustomHttpContext.Items);
Assert.Same(httpContext.Features, controller.CustomHttpContext.Features);
Assert.Same(httpContext.RequestServices, controller.CustomHttpContext.RequestServices);
Assert.Same(httpContext.Session, controller.CustomHttpContext.Session);
Assert.Same(httpContext.TraceIdentifier, controller.CustomHttpContext.TraceIdentifier);
Assert.Same(httpContext.User, controller.CustomHttpContext.User);
});
MyApplication.StartsFrom<DefaultStartup>();
}
开发者ID:ivaylokenov,项目名称:MyTested.AspNetCore.Mvc,代码行数:58,代码来源:ControllerBuilderTests.cs
注:本文中的Microsoft.AspNetCore.Http.DefaultHttpContext类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论