public async Task ExecuteResultAsync_Throws_IfViewCouldNotBeFound_MessageUsesGetViewLocations() { // Arrange var expected = string.Join( Environment.NewLine, "The view 'MyView' was not found. The following locations were searched:", "Location1", "Location2"); var actionContext = GetActionContext(); var viewEngine = new Mock<IViewEngine>(MockBehavior.Strict); viewEngine .Setup(e => e.GetView(/*executingFilePath*/ null, "MyView", /*isMainPage*/ true)) .Returns(ViewEngineResult.NotFound("MyView", new[] { "Location1", "Location2" })) .Verifiable(); viewEngine .Setup(v => v.FindView(It.IsAny<ActionContext>(), It.IsAny<string>(), /*isMainPage*/ true)) .Returns(ViewEngineResult.NotFound("MyView", Enumerable.Empty<string>())) .Verifiable(); var viewResult = new ViewResult { ViewEngine = viewEngine.Object, ViewName = "MyView", ViewData = new ViewDataDictionary(new EmptyModelMetadataProvider()), TempData = Mock.Of<ITempDataDictionary>(), }; // Act and Assert var ex = await Assert.ThrowsAsync<InvalidOperationException>( () => viewResult.ExecuteResultAsync(actionContext)); Assert.Equal(expected, ex.Message); viewEngine.Verify(); }
/// <inheritdoc/> public async Task ExecuteResultAsync(ActionContext context) { HttpResponse response = context.HttpContext.Response; response.Clear(); response.StatusCode = StatusCodes.Status404NotFound; IPublishedRequest frequest = _umbracoContext.PublishedRequest; var reason = "Cannot render the page at URL '{0}'."; if (frequest.HasPublishedContent() == false) { reason = "No umbraco document matches the URL '{0}'."; } else if (frequest.HasTemplate() == false) { reason = "No template exists to render the document at URL '{0}'."; } var viewResult = new ViewResult { ViewName = "~/umbraco/UmbracoWebsite/NotFound.cshtml" }; context.HttpContext.Items.Add("reason", string.Format(reason, WebUtility.HtmlEncode(_umbracoContext.OriginalRequestUrl.PathAndQuery))); context.HttpContext.Items.Add("message", _message); await viewResult.ExecuteResultAsync(context); }
public async Task Invoke(HttpContext context) { var actionContext = new ActionContext { HttpContext = context }; if (!context.Response.HasStarted) { if (context.Response.StatusCode == StatusCodes.Status404NotFound) { var view = new ViewResult(); view.ViewName = "Error404"; await view.ExecuteResultAsync(actionContext); } if (context.Response.StatusCode == StatusCodes.Status500InternalServerError) { var view = new ViewResult(); view.ViewName = "Error500"; await view.ExecuteResultAsync(actionContext); } if (context.Response.StatusCode == StatusCodes.Status400BadRequest) { var view = new ViewResult(); view.ViewName = "Error400"; await view.ExecuteResultAsync(actionContext); } } await _next(context); }
public async Task ExecuteResultAsync(ActionContext context) { if (context.HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest") { var jsonResult = new JsonResult(_feedback); if (_feedback.Tipo == TipoFeedback.Erro || _feedback.Tipo == TipoFeedback.Atencao) { jsonResult.StatusCode = (int)HttpStatusCode.BadRequest; } await jsonResult.ExecuteResultAsync(context); } else { var viewResult = new ViewResult { ViewName = "_Feedback", ViewData = new ViewDataDictionary(new EmptyModelMetadataProvider(), context.ModelState) { Model = _feedback } }; await viewResult.ExecuteResultAsync(context); } }
public async Task ExecuteResultAsync_WritesOutputWithoutBOM() { // Arrange var expected = new byte[] { 97, 98, 99, 100 }; var view = new Mock <IView>(); view.Setup(v => v.RenderAsync(It.IsAny <ViewContext>())) .Callback((ViewContext v) => { view.ToString(); v.Writer.Write("abcd"); }) .Returns(Task.FromResult(0)); var routeDictionary = new Dictionary <string, object>(); var viewEngine = new Mock <ICompositeViewEngine>(); var serviceProvider = new Mock <IServiceProvider>(); serviceProvider.Setup(sp => sp.GetService(typeof(ICompositeViewEngine))) .Returns(viewEngine.Object); 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); context.SetupGet(c => c.RequestServices) .Returns(serviceProvider.Object); var actionContext = new ActionContext(context.Object, new RouteData() { Values = routeDictionary }, new ActionDescriptor()); viewEngine.Setup(v => v.FindView(actionContext, It.IsAny <string>())) .Returns(ViewEngineResult.Found("MyView", view.Object)); var viewResult = new ViewResult(); // Act await viewResult.ExecuteResultAsync(actionContext); // Assert Assert.Equal(expected, memoryStream.ToArray()); }
/// <summary> /// Handle exception. /// </summary> /// <param name="context">The cu<see cref="Filters.ExceptionContext"/>.</param> /// <returns>The task to handle exception.</returns> public override async Task OnExceptionAsync(Filters.ExceptionContext context) { Guard.ArgumentNotNull(context, nameof(context)); context.ExceptionHandled = true; _options = context.HttpContext.RequestServices.GetRequiredService <IOptions <HandleExceptionFilterOptions> >().Value; if (context.Exception == null) { return; } ExceptionManager manager = context.HttpContext.RequestServices.GetRequiredService <ExceptionManager>(); string exceptionPolicy = this.GetExceptionPolicy(context); try { if (!string.IsNullOrEmpty(exceptionPolicy)) { await manager.HandleExceptionAsync(context.Exception, exceptionPolicy); } else { manager.HandleExceptionAsync(context.Exception).Wait(); } } catch (Exception ex) { ex = (ex as AggregateException)?.InnerException ?? ex; var exceptionInfo = new ExceptionInfo(ex, _options.IncludeInnerException); if (this.TryGetHandlerAction(context, out ActionDescriptor handlerAction)) { context.HttpContext.SetExceptionInfo(exceptionInfo); ActionContext actionContext = new ActionContext(context.HttpContext, context.RouteData, handlerAction); IActionInvoker actionInvoker = context.HttpContext.RequestServices.GetRequiredService <IActionInvokerFactory>().CreateInvoker(actionContext); await actionInvoker.InvokeAsync(); return; } if (context.HttpContext.IsAjaxRequest()) { JsonResult json = new JsonResult(exceptionInfo, _options.JsonSerializerSettings); await json.ExecuteResultAsync(new ActionContext(context)); return; } var viewData = new ViewDataDictionary(new EmptyModelMetadataProvider(), context.ModelState) { Model = exceptionInfo }; ViewResult view = new ViewResult { ViewData = viewData }; await view.ExecuteResultAsync(context); } }
public async Task ExecuteResultAsync_DoesNotWriteToResponse_OnceExceptionIsThrown(int writtenLength, int expectedLength) { // Arrange var longString = new string('a', writtenLength); var routeDictionary = new Dictionary <string, object>(); var view = new Mock <IView>(); view.Setup(v => v.RenderAsync(It.IsAny <ViewContext>())) .Callback((ViewContext v) => { view.ToString(); v.Writer.Write(longString); throw new Exception(); }); var viewEngine = new Mock <ICompositeViewEngine>(); viewEngine.Setup(v => v.FindView(It.IsAny <ActionContext>(), It.IsAny <string>())) .Returns(ViewEngineResult.Found("MyView", view.Object)); var serviceProvider = new Mock <IServiceProvider>(); serviceProvider.Setup(sp => sp.GetService(typeof(ICompositeViewEngine))) .Returns(viewEngine.Object); 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); context.SetupGet(c => c.RequestServices).Returns(serviceProvider.Object); var actionContext = new ActionContext(context.Object, new RouteData() { Values = routeDictionary }, new ActionDescriptor()); var viewResult = new ViewResult(); // Act await Record.ExceptionAsync(() => viewResult.ExecuteResultAsync(actionContext)); // Assert Assert.Equal(expectedLength, memoryStream.Length); }
public async Task ExecuteResultAsync_FindsAndExecutesView() { // Arrange var viewName = "MyView"; var actionContext = GetActionContext(); var view = new Mock <IView>(MockBehavior.Strict); view .Setup(v => v.RenderAsync(It.IsAny <ViewContext>())) .Returns(Task.FromResult(0)) .Verifiable(); view .As <IDisposable>() .Setup(v => v.Dispose()) .Verifiable(); // Used by logging view .SetupGet(v => v.Path) .Returns($"{viewName}.cshtml"); var viewEngine = new Mock <IViewEngine>(MockBehavior.Strict); viewEngine .Setup(v => v.GetView(/*executingFilePath*/ null, viewName, /*isMainPage*/ true)) .Returns(ViewEngineResult.NotFound(viewName, Enumerable.Empty <string>())) .Verifiable(); viewEngine .Setup(v => v.FindView(It.IsAny <ActionContext>(), viewName, /*isMainPage*/ true)) .Returns(ViewEngineResult.Found(viewName, view.Object)) .Verifiable(); var viewResult = new ViewResult { ViewName = viewName, ViewEngine = viewEngine.Object, ViewData = new ViewDataDictionary(new EmptyModelMetadataProvider()), TempData = Mock.Of <ITempDataDictionary>(), }; // Act await viewResult.ExecuteResultAsync(actionContext); // Assert view.Verify(); viewEngine.Verify(); }
internal static Task View(this HttpResponse response, string viewName, object model, ViewDataDictionary viewData) { if (model != null) { viewData.Model = model; } var viewResult = new ViewResult() { ViewName = viewName, ViewData = viewData }; return(viewResult.ExecuteResultAsync(new ActionContext(response.HttpContext, new RouteData(), new ActionDescriptor()))); }
public async Task ExecuteResultAsync_WritesOutputWithoutBOM() { // Arrange var expected = new byte[] { 97, 98, 99, 100 }; var view = new Mock<IView>(); view.Setup(v => v.RenderAsync(It.IsAny<ViewContext>())) .Callback((ViewContext v) => { view.ToString(); v.Writer.Write("abcd"); }) .Returns(Task.FromResult(0)); var routeDictionary = new Dictionary<string, object>(); var viewEngine = new Mock<ICompositeViewEngine>(); var serviceProvider = new Mock<IServiceProvider>(); serviceProvider.Setup(sp => sp.GetService(typeof(ICompositeViewEngine))) .Returns(viewEngine.Object); 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); context.SetupGet(c => c.RequestServices) .Returns(serviceProvider.Object); var actionContext = new ActionContext(context.Object, new RouteData() { Values = routeDictionary }, new ActionDescriptor()); viewEngine.Setup(v => v.FindView(actionContext, It.IsAny<string>())) .Returns(ViewEngineResult.Found("MyView", view.Object)); var viewResult = new ViewResult(); // Act await viewResult.ExecuteResultAsync(actionContext); // Assert Assert.Equal(expected, memoryStream.ToArray()); }
public async Task ExecuteResultAsync_Throws_IfServicesNotRegistered() { // Arrange var actionContext = new ActionContext(new DefaultHttpContext() { RequestServices = Mock.Of <IServiceProvider>(), }, new RouteData(), new ActionDescriptor()); var expected = $"Unable to find the required services. Please add all the required services by calling " + $"'IServiceCollection.AddControllersWithViews()' inside the call to 'ConfigureServices(...)' " + $"in the application startup code."; var viewResult = new ViewResult(); // Act var ex = await Assert.ThrowsAsync <InvalidOperationException>(() => viewResult.ExecuteResultAsync(actionContext)); // Assert Assert.Equal(expected, ex.Message); }
public async Task ExecuteResultAsync_Throws_IfViewCouldNotBeFound_MessageUsesAllLocations() { // Arrange var viewName = "MyView"; var actionContext = GetActionContext(); var expected = string.Join( Environment.NewLine, $"The view '{viewName}' was not found. The following locations were searched:", "Location1", "Location2", "Location3", "Location4"); var viewEngine = new Mock <IViewEngine>(MockBehavior.Strict); viewEngine .Setup(v => v.GetView(/*executingFilePath*/ null, viewName, /*isMainPage*/ true)) .Returns(ViewEngineResult.NotFound(viewName, new[] { "Location1", "Location2" })) .Verifiable(); viewEngine .Setup(v => v.FindView(It.IsAny <ActionContext>(), viewName, /*isMainPage*/ true)) .Returns(ViewEngineResult.NotFound(viewName, new[] { "Location3", "Location4" })) .Verifiable(); var viewResult = new ViewResult { ViewEngine = viewEngine.Object, ViewName = viewName, ViewData = new ViewDataDictionary(new EmptyModelMetadataProvider()), TempData = Mock.Of <ITempDataDictionary>(), }; // Act and Assert var ex = await Assert.ThrowsAsync <InvalidOperationException>( () => viewResult.ExecuteResultAsync(actionContext)); Assert.Equal(expected, ex.Message); viewEngine.Verify(); }
public Task ExecuteViewAsync(HttpContext context, string viewName, object model = null, int statusCode = 200) { var result = new ViewResult() { StatusCode = statusCode, ViewName = viewName }; var modelStateDictionary = new ModelStateDictionary(); result.ViewData = new ViewDataDictionary(new EmptyModelMetadataProvider(), modelStateDictionary) { Model = model }; var routeData = new RouteData(); var actionDescriptor = new ActionDescriptor(); var actionContext = new ActionContext(context, routeData, actionDescriptor); return(result.ExecuteResultAsync(actionContext)); }
public async Task ViewResult_UsesFindViewOnSpecifiedViewEngineToLocateViews() { // Arrange var viewName = "myview"; var context = new ActionContext(new DefaultHttpContext(), new RouteData(), new ActionDescriptor()); var viewEngine = new Mock <IViewEngine>(); var view = Mock.Of <IView>(); viewEngine.Setup(e => e.FindView(context, "myview")) .Returns(ViewEngineResult.Found("myview", view)) .Verifiable(); var viewResult = new ViewResult { ViewName = viewName, ViewEngine = viewEngine.Object }; // Act await viewResult.ExecuteResultAsync(context); // Assert viewEngine.Verify(); }
public async Task ExecuteResultAsync_FindsAndExecutesView() { // Arrange var viewName = "myview"; var context = GetActionContext(); var view = new Mock<IView>(MockBehavior.Strict); view .Setup(v => v.RenderAsync(It.IsAny<ViewContext>())) .Returns(Task.FromResult(0)) .Verifiable(); view .As<IDisposable>() .Setup(v => v.Dispose()) .Verifiable(); view .Setup(v => v.Path) .Returns("//location"); var viewEngine = new Mock<IViewEngine>(MockBehavior.Strict); viewEngine .Setup(e => e.GetView(/*executingFilePath*/ null, "myview", /*isMainPage*/ true)) .Returns(ViewEngineResult.NotFound("myview", Enumerable.Empty<string>())) .Verifiable(); viewEngine .Setup(e => e.FindView(context, "myview", /*isMainPage*/ true)) .Returns(ViewEngineResult.Found("myview", view.Object)) .Verifiable(); var viewResult = new ViewResult { ViewName = viewName, ViewEngine = viewEngine.Object, ViewData = new ViewDataDictionary(new EmptyModelMetadataProvider()), TempData = Mock.Of<ITempDataDictionary>(), }; // Act await viewResult.ExecuteResultAsync(context); // Assert view.Verify(); viewEngine.Verify(); }
public async Task ExecuteResultAsync_DoesNotWriteToResponse_OnceExceptionIsThrown(int writtenLength, int expectedLength) { // Arrange var longString = new string('a', writtenLength); var routeDictionary = new Dictionary<string, object>(); var view = new Mock<IView>(); view.Setup(v => v.RenderAsync(It.IsAny<ViewContext>())) .Callback((ViewContext v) => { view.ToString(); v.Writer.Write(longString); throw new Exception(); }); var viewEngine = new Mock<ICompositeViewEngine>(); viewEngine.Setup(v => v.FindView(It.IsAny<ActionContext>(), It.IsAny<string>())) .Returns(ViewEngineResult.Found("MyView", view.Object)); var serviceProvider = new Mock<IServiceProvider>(); serviceProvider.Setup(sp => sp.GetService(typeof(ICompositeViewEngine))) .Returns(viewEngine.Object); 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); context.SetupGet(c => c.RequestServices).Returns(serviceProvider.Object); var actionContext = new ActionContext(context.Object, new RouteData() { Values = routeDictionary }, new ActionDescriptor()); var viewResult = new ViewResult(); // Act await Record.ExceptionAsync(() => viewResult.ExecuteResultAsync(actionContext)); // Assert Assert.Equal(expectedLength, memoryStream.Length); }