本文整理汇总了C#中Microsoft.AspNet.Mvc.ActionContext类的典型用法代码示例。如果您正苦于以下问题:C# ActionContext类的具体用法?C# ActionContext怎么用?C# ActionContext使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
ActionContext类属于Microsoft.AspNet.Mvc命名空间,在下文中一共展示了ActionContext类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GetViewDataDictionary
private ViewDataDictionary GetViewDataDictionary(ActionContext context)
{
var serviceProvider = context.HttpContext.RequestServices;
return new ViewDataDictionary(
_modelMetadataProvider,
context.ModelState);
}
示例2: ExecuteResultAsync
/// <inheritdoc />
public override Task ExecuteResultAsync(ActionContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
var loggerFactory = context.HttpContext.RequestServices.GetRequiredService<ILoggerFactory>();
var logger = loggerFactory.CreateLogger<FileResult>();
var response = context.HttpContext.Response;
response.ContentType = ContentType.ToString();
if (!string.IsNullOrEmpty(FileDownloadName))
{
// From RFC 2183, Sec. 2.3:
// The sender may want to suggest a filename to be used if the entity is
// detached and stored in a separate file. If the receiving MUA writes
// the entity to a file, the suggested filename should be used as a
// basis for the actual filename, where possible.
var contentDisposition = new ContentDispositionHeaderValue("attachment");
contentDisposition.SetHttpFileName(FileDownloadName);
context.HttpContext.Response.Headers[HeaderNames.ContentDisposition] = contentDisposition.ToString();
}
logger.FileResultExecuting(FileDownloadName);
return WriteFileAsync(response);
}
示例3: Create_TypeActivatesTypesWithServices
public void Create_TypeActivatesTypesWithServices()
{
// Arrange
var activator = new DefaultControllerActivator(new DefaultTypeActivatorCache());
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 actionContext = new ActionContext(httpContext,
new RouteData(),
new ActionDescriptor());
// Act
var instance = activator.Create(actionContext, typeof(TypeDerivingFromControllerWithServices));
// Assert
var controller = Assert.IsType<TypeDerivingFromControllerWithServices>(instance);
Assert.Same(testService, controller.TestService);
serviceProvider.Verify();
}
示例4: ExecuteResultAsync_FallsBackToThePhysicalFileProvider_IfNoFileProviderIsPresent
public async Task ExecuteResultAsync_FallsBackToThePhysicalFileProvider_IfNoFileProviderIsPresent()
{
// Arrange
var path = Path.Combine("TestFiles", "FilePathResultTestFile.txt");
var result = new FilePathResult(path, "text/plain");
var appEnvironment = new Mock<IHostingEnvironment>();
appEnvironment.Setup(app => app.WebRootFileProvider)
.Returns(new PhysicalFileProvider(Directory.GetCurrentDirectory()));
var httpContext = new DefaultHttpContext();
httpContext.Response.Body = new MemoryStream();
httpContext.RequestServices = new ServiceCollection()
.AddInstance<IHostingEnvironment>(appEnvironment.Object)
.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);
}
示例5: ExecuteResultAsync
public override Task ExecuteResultAsync(ActionContext context)
{
var webSocket = context.HttpContext.WebSockets.AcceptWebSocketAsync().Result;
BlockingStream stream = new BlockingStream(16);
//Read from stream as it comes in.
Task.Factory.StartNew(() => _streamHandlerAction(stream));
var receive = Task.Factory.StartNew(() =>
{
byte[] buffer = new byte[1024 * 63];
while (true)
{
// MUST read if we want the state to get updated...
var result = webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None).Result;
stream.Write(buffer, 0, result.Count);
if (result.MessageType == WebSocketMessageType.Close)
{
webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, String.Empty, CancellationToken.None);
stream.CompleteWriting();
break;
}
}
});
return receive;
}
示例6: OnFormatting
/// <inheritdoc />
public override void OnFormatting(ActionContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
base.OnFormatting(context);
var urlHelper = UrlHelper;
if (urlHelper == null)
{
var services = context.HttpContext.RequestServices;
urlHelper = services.GetRequiredService<IUrlHelperFactory>().GetUrlHelper(context);
}
var url = urlHelper.Link(RouteName, RouteValues);
if (string.IsNullOrEmpty(url))
{
throw new InvalidOperationException(Resources.NoRoutesMatched);
}
context.HttpContext.Response.Headers[HeaderNames.Location] = url;
}
示例7: ExecuteResultAsync_ReturnsError_IfViewCouldNotBeFound
public async Task ExecuteResultAsync_ReturnsError_IfViewCouldNotBeFound()
{
// Arrange
var expected = string.Join(Environment.NewLine,
"The view 'MyView' was not found. The following locations were searched:",
"Location1",
"Location2.");
var actionContext = new ActionContext(GetHttpContext(),
new RouteData(),
new ActionDescriptor());
var viewEngine = new Mock<IViewEngine>();
viewEngine.Setup(v => v.FindPartialView(It.IsAny<ActionContext>(), It.IsAny<string>()))
.Returns(ViewEngineResult.NotFound("MyView", new[] { "Location1", "Location2" }))
.Verifiable();
var viewResult = new PartialViewResult
{
ViewEngine = viewEngine.Object,
ViewName = "MyView"
};
// Act and Assert
var ex = await Assert.ThrowsAsync<InvalidOperationException>(
() => viewResult.ExecuteResultAsync(actionContext));
Assert.Equal(expected, ex.Message);
viewEngine.Verify();
}
示例8: ExecuteResultAsync_InvokesForbiddenAsyncOnAllConfiguredSchemes
public async Task ExecuteResultAsync_InvokesForbiddenAsyncOnAllConfiguredSchemes()
{
// Arrange
var authProperties = new AuthenticationProperties();
var authenticationManager = new Mock<AuthenticationManager>();
authenticationManager
.Setup(c => c.ForbidAsync("Scheme1", authProperties))
.Returns(TaskCache.CompletedTask)
.Verifiable();
authenticationManager
.Setup(c => c.ForbidAsync("Scheme2", 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 ForbidResult(new[] { "Scheme1", "Scheme2" }, authProperties);
var routeData = new RouteData();
var actionContext = new ActionContext(
httpContext.Object,
routeData,
new ActionDescriptor());
// Act
await result.ExecuteResultAsync(actionContext);
// Assert
authenticationManager.Verify();
}
示例9: BindActionArgumentsAsync
public async Task<IDictionary<string, object>> BindActionArgumentsAsync(
ActionContext actionContext,
ActionBindingContext actionBindingContext,
object controller)
{
var actionDescriptor = actionContext.ActionDescriptor as ControllerActionDescriptor;
if (actionDescriptor == null)
{
throw new ArgumentException(
Resources.FormatActionDescriptorMustBeBasedOnControllerAction(
typeof(ControllerActionDescriptor)),
nameof(actionContext));
}
var operationBindingContext = GetOperationBindingContext(actionContext, actionBindingContext);
var controllerProperties = new Dictionary<string, object>(StringComparer.Ordinal);
await PopulateArgumentsAsync(
operationBindingContext,
actionContext.ModelState,
controllerProperties,
actionDescriptor.BoundProperties);
var controllerType = actionDescriptor.ControllerTypeInfo.AsType();
ActivateProperties(controller, controllerType, controllerProperties);
var actionArguments = new Dictionary<string, object>(StringComparer.Ordinal);
await PopulateArgumentsAsync(
operationBindingContext,
actionContext.ModelState,
actionArguments,
actionDescriptor.Parameters);
return actionArguments;
}
示例10: ExecuteResultAsync
/// <inheritdoc />
public override Task ExecuteResultAsync(ActionContext context)
{
var response = context.HttpContext.Response;
response.ContentType = ContentType.Bson;
if (StatusCode != null)
{
response.StatusCode = StatusCode.Value;
}
var serializerSettings = _serializerSettings;
if (serializerSettings == null)
{
serializerSettings = context
.HttpContext
.RequestServices
.GetRequiredService<IOptions<MvcJsonOptions>>()
.Value
.SerializerSettings;
}
using (var bsonWriter = new BsonWriter(response.Body))
{
bsonWriter.CloseOutput = false;
var jsonSerializer = JsonSerializer.Create(serializerSettings);
jsonSerializer.Serialize(bsonWriter, Value);
}
return Task.FromResult(true);
}
示例11: ExecuteResult_UsesEncoderIfSpecified
public async Task ExecuteResult_UsesEncoderIfSpecified()
{
// Arrange
var expected = Enumerable.Concat(Encoding.UTF8.GetPreamble(), _abcdUTF8Bytes);
var memoryStream = new MemoryStream();
var response = new Mock<HttpResponse>();
response.SetupGet(r => r.Body)
.Returns(memoryStream);
var context = new Mock<HttpContext>();
context.SetupGet(c => c.Response)
.Returns(response.Object);
var actionContext = new ActionContext(context.Object,
new RouteData(),
new ActionDescriptor());
var result = new JsonResult(new { foo = "abcd" })
{
Encoding = Encoding.UTF8
};
// Act
await result.ExecuteResultAsync(actionContext);
// Assert
Assert.Equal(expected, memoryStream.ToArray());
}
示例12: ExecuteResultAsync
public override Task ExecuteResultAsync(ActionContext context)
{
var executor = context.HttpContext.RequestServices.GetRequiredService<ObjectResultExecutor>();
var result = executor.ExecuteAsync(context, this);
return result;
}
示例13: ObjectResult_ExecuteResultAsync_SetsStatusCode
public async Task ObjectResult_ExecuteResultAsync_SetsStatusCode()
{
// Arrange
var result = new ObjectResult("Hello")
{
StatusCode = 404,
Formatters = new List<IOutputFormatter>()
{
new NoOpOutputFormatter(),
},
};
var actionContext = new ActionContext()
{
HttpContext = new DefaultHttpContext()
{
RequestServices = CreateServices(),
}
};
// Act
await result.ExecuteResultAsync(actionContext);
// Assert
Assert.Equal(404, actionContext.HttpContext.Response.StatusCode);
}
示例14: ExecuteResultAsync
public async Task ExecuteResultAsync(ActionContext context)
{
var routeDef = context.RouteData.DataTokens.ContainsKey("umbraco-route-def")
? context.RouteData.DataTokens["umbraco-route-def"] as RouteDefinition
: null;
if (routeDef == null)
throw new InvalidOperationException($"The route data DataTokens must contain an instance of {typeof(RouteDefinition)} with a key of umbraco-route-def");
var actionFactory = context.HttpContext.RequestServices
.GetService<IActionInvokerFactory>();
var providers = context.HttpContext.RequestServices
.GetService<IActionDescriptorsCollectionProvider>();
var actionDesc = providers.ActionDescriptors
.Items
.OfType<ControllerActionDescriptor>()
.First(x => x.ControllerName.InvariantEquals(routeDef.ControllerName) && x.Name.InvariantEquals(routeDef.ActionName));
var copied = new ActionContext(context.HttpContext, context.RouteData, actionDesc);
copied.ModelState.Merge(context.ModelState);
copied.RouteData.DataTokens["umbraco-vdd"] = _vdd;
await actionFactory.CreateInvoker(copied).InvokeAsync();
}
示例15: ExecuteResultAsync
public override Task ExecuteResultAsync(ActionContext context) {
if(context == null) {
throw new ArgumentNullException(nameof(context));
}
return iCalendarOutputFormatter.WriteResponseBodyAsync(context.HttpContext.Response, _uid, _datetime, _duration, _summary, _description, _location);
}