本文整理汇总了C#中Microsoft.AspNetCore.Mvc.ActionContext类的典型用法代码示例。如果您正苦于以下问题:C# ActionContext类的具体用法?C# ActionContext怎么用?C# ActionContext使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
ActionContext类属于Microsoft.AspNetCore.Mvc命名空间,在下文中一共展示了ActionContext类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ExecuteResultAsync
public override async Task ExecuteResultAsync(ActionContext context)
{
var response = context.HttpContext.Response;
response.ContentType = ContentType;
var targetStream = response.Body;
if (CopyStream != null)
{
await Task.Factory.StartNew(() =>
{
CopyStream(targetStream);
});
}
else if (Content != null)
{
await targetStream.WriteAsync(Content, 0, Content.Length);
}
else
{
using (SourceStream)
{
if (SourceStream.CanSeek)
{
SourceStream.Seek(0, SeekOrigin.Begin);
}
await SourceStream.CopyToAsync(targetStream);
}
}
}
示例2: ExecuteResultAsync_InvokesSignOutAsyncOnAuthenticationManager
public async Task ExecuteResultAsync_InvokesSignOutAsyncOnAuthenticationManager()
{
// Arrange
var authenticationManager = new Mock<AuthenticationManager>();
authenticationManager
.Setup(c => c.SignOutAsync("", null))
.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 SignOutResult("", null);
var routeData = new RouteData();
var actionContext = new ActionContext(
httpContext.Object,
routeData,
new ActionDescriptor());
// Act
await result.ExecuteResultAsync(actionContext);
// Assert
authenticationManager.Verify();
}
示例3: 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);
}
}
示例4: ExecuteResultAsync
public override Task ExecuteResultAsync(ActionContext context)
{
var executor = context.HttpContext.RequestServices.GetRequiredService<ObjectResultExecutor>();
var result = executor.ExecuteAsync(context, this);
return result;
}
示例5: FromActionContext
public static ViewContext FromActionContext(HttpTestContext testContext, ActionContext actionContext)
=> FromViewContext(testContext, new ViewContext
{
HttpContext = actionContext.HttpContext,
RouteData = actionContext.RouteData,
ActionDescriptor = actionContext.ActionDescriptor,
});
示例6: ExecuteResultAsync
public async Task ExecuteResultAsync(ActionContext actionContext) {
using (_pipe) {
var context = actionContext.HttpContext;
var httpResponse = context.Features.Get<IHttpResponseFeature>();
if (!context.WebSockets.IsWebSocketRequest) {
httpResponse.ReasonPhrase = "Websocket connection expected";
httpResponse.StatusCode = 401;
return;
}
using (var socket = await context.WebSockets.AcceptWebSocketAsync("Microsoft.R.Host")) {
Task wsToPipe, pipeToWs, completed;
var cts = CancellationTokenSource.CreateLinkedTokenSource(context.RequestAborted);
wsToPipe = WebSocketToPipeWorker(socket, _pipe, cts.Token);
pipeToWs = PipeToWebSocketWorker(socket, _pipe, cts.Token);
completed = await Task.WhenAny(wsToPipe, pipeToWs);
if (completed == pipeToWs) {
// If the pipe end is exhausted, tell the client that there's no more messages to follow,
// so that it can gracefully disconnect from its end.
await socket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "", context.RequestAborted);
} else {
// If the client disconnected, then just cancel any outstanding reads from the pipe.
cts.Cancel();
}
}
}
}
示例7: BuildMenu
public IEnumerable<MenuItem> BuildMenu(string name, ActionContext actionContext)
{
var builder = new NavigationBuilder();
// Processes all navigation builders to create a flat list of menu items.
// If a navigation builder fails, it is ignored.
foreach (var navigationProvider in _navigationProviders)
{
try
{
navigationProvider.BuildNavigation(name, builder);
}
catch (Exception e)
{
_logger.LogError($"An exception occured while building the menu: {name}", e);
}
}
var menuItems = builder.Build();
// Merge all menu hierarchies into a single one
Merge(menuItems);
// Remove unauthorized menu items
menuItems = Reduce(menuItems, null);
// Compute Url and RouteValues properties to Href
menuItems = ComputeHref(menuItems, actionContext);
return menuItems;
}
示例8: 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 = GetHttpContext();
httpContext.Response.Body = mockBodyStream.Object;
var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor());
// Act
await result.ExecuteResultAsync(actionContext);
// Assert
mockReadStream.Verify();
mockBodyStream.Verify();
}
示例9: RedirectToAction_Execute_PassesCorrectValuesToRedirect
public async void RedirectToAction_Execute_PassesCorrectValuesToRedirect()
{
// 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 RedirectToActionResult("SampleAction", null, null)
{
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));
}
示例10: 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;
}
示例11: ExecuteResultAsync_InvokesSignInAsyncOnConfiguredScheme
public async Task ExecuteResultAsync_InvokesSignInAsyncOnConfiguredScheme()
{
// Arrange
var principal = new ClaimsPrincipal();
var authProperties = new AuthenticationProperties();
var authenticationManager = new Mock<AuthenticationManager>();
authenticationManager
.Setup(c => c.SignInAsync("Scheme1", principal, 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 SignInResult("Scheme1", principal, authProperties);
var routeData = new RouteData();
var actionContext = new ActionContext(
httpContext.Object,
routeData,
new ActionDescriptor());
// Act
await result.ExecuteResultAsync(actionContext);
// Assert
authenticationManager.Verify();
}
示例12: ExecuteProblemResultAsync
private async Task ExecuteProblemResultAsync(HttpContext context, Problem problem)
{
var actionContext = new ActionContext(context, new RouteData(), new ActionDescriptor());
var executor = context.RequestServices.GetService<ObjectResultExecutor>() ?? _objectResultExecutor;
var result = new ProblemResult(problem);
await result.ExecuteResultAsync(executor, actionContext);
}
示例13: ExecuteResultAsync_FallsBackToWebRootFileProvider_IfNoFileProviderIsPresent
public async Task ExecuteResultAsync_FallsBackToWebRootFileProvider_IfNoFileProviderIsPresent()
{
// Arrange
var path = Path.Combine("TestFiles", "FilePathResultTestFile.txt");
var result = new TestVirtualFileResult(path, "text/plain");
var appEnvironment = new Mock<IHostingEnvironment>();
appEnvironment.Setup(app => app.WebRootFileProvider)
.Returns(GetFileProvider(path));
var httpContext = GetHttpContext();
httpContext.Response.Body = new MemoryStream();
httpContext.RequestServices = new ServiceCollection()
.AddSingleton<IHostingEnvironment>(appEnvironment.Object)
.AddTransient<ILoggerFactory, LoggerFactory>()
.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);
}
示例14: ExecuteResultAsync
public Task ExecuteResultAsync(ActionContext context)
{
context.HttpContext.Response.StatusCode = StatusCodes.Status200OK;
context.HttpContext.Response.ContentType = "text/plain";
context.HttpContext.Response.ContentLength = _helloWorldPayload.Length;
return context.HttpContext.Response.Body.WriteAsync(_helloWorldPayload, 0, _helloWorldPayload.Length);
}
示例15: ExecuteResultAsync
/// <inheritdoc />
public override async Task ExecuteResultAsync(ActionContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (AuthenticationSchemes == null)
{
throw new InvalidOperationException(
Resources.FormatPropertyOfTypeCannotBeNull(
/* property: */ nameof(AuthenticationSchemes),
/* type: */ nameof(SignOutResult)));
}
if (AuthenticationSchemes.Count == 0)
{
throw new ArgumentException(Resources.MustSpecifyAtLeastOneAuthenticationScheme, nameof(AuthenticationSchemes));
}
var loggerFactory = context.HttpContext.RequestServices.GetRequiredService<ILoggerFactory>();
var logger = loggerFactory.CreateLogger<SignOutResult>();
logger.SignOutResultExecuting(AuthenticationSchemes);
var authentication = context.HttpContext.Authentication;
for (var i = 0; i < AuthenticationSchemes.Count; i++)
{
await authentication.SignOutAsync(AuthenticationSchemes[i], Properties);
}
}