private static Models.Action ParseAction(Microsoft.AspNetCore.Mvc.Abstractions.ActionDescriptor actionDescriptor) { var action = new Models.Action { Template = actionDescriptor.AttributeRouteInfo.Template, Parameters = actionDescriptor.Parameters .Select(p => new Parameter { Name = p.Name, Type = p.ParameterType.FullName }) .ToList() }; if (actionDescriptor.ActionConstraints != null) { for (var i = 0; i < actionDescriptor.ActionConstraints.Count; i++) { var actionDescriptorActionConstraint = actionDescriptor.ActionConstraints[i]; if (actionDescriptorActionConstraint is HttpMethodActionConstraint httpMethodActionConstraint) { action.Methods.AddRange(httpMethodActionConstraint.HttpMethods); } } } return(action); }
public static string GetShortMethodName(this Microsoft.AspNetCore.Mvc.Abstractions.ActionDescriptor actionDescriptor) { var splitedDisplayName = actionDescriptor.DisplayName.Split("("); var splitedMethodName = splitedDisplayName[0].Split("."); var shortMethodName = splitedMethodName[splitedMethodName.Length - 2].Trim() + "." + splitedMethodName[splitedMethodName.Length - 1].Trim(); return(shortMethodName); }
public static IEnumerable <T> GetCustomAttributes <T>(this Microsoft.AspNetCore.Mvc.Abstractions.ActionDescriptor actionDescriptor) where T : Attribute { var controllerActionDescriptor = actionDescriptor as ControllerActionDescriptor; if (controllerActionDescriptor != null) { return(controllerActionDescriptor.MethodInfo.ReflectedType.GetCustomAttributes(typeof(T), true).Select(a => (T)a)); } return(Enumerable.Empty <T>()); }
string InspectAndFormat(Microsoft.AspNetCore.Mvc.Abstractions.ActionDescriptor a, Exception e) { var timings = new List <string>(); var timer = Stopwatch.StartNew(); var displayName = a.DisplayName; timings.Add("Name:" + timer.ElapsedMilliseconds); var constraints = a.ActionConstraints.ToJson(); timings.Add("Constraints:" + timer.ElapsedMilliseconds); var attributeRouteInfo = a.AttributeRouteInfo?.ToJson(); timings.Add("AttributeRouteInfo:" + timer.ElapsedMilliseconds); var boundProperties = a.BoundProperties?.ToJson(); timings.Add("BoundProperties:" + timer.ElapsedMilliseconds); var filterDescriptors = a.FilterDescriptors?.Select( fd => new{ FilterType = fd.Filter.GetType().FullName, fd.Order, fd.Scope }).ToJson(); timings.Add("FilterDescriptors:" + timer.ElapsedMilliseconds); var parameters = a.Parameters?.Select( p => new { p.Name, TypeName = p.ParameterType.FullName, BindingInfo = new { p.BindingInfo?.BinderModelName, BinderType = p.BindingInfo?.BinderType.FullName, p.BindingInfo?.BindingSource, PropertyFilterProviderType = p.BindingInfo?.PropertyFilterProvider.GetType().FullName, RequestPredicateMethodDeclaringType = p.BindingInfo?.RequestPredicate.Method.DeclaringType?.FullName, } } ).ToJson(); timings.Add("Parameters:" + timer.ElapsedMilliseconds); var properties = a.Properties?.ToJson(); timings.Add("Properties:" + timer.ElapsedMilliseconds); var routeValues = a.RouteValues?.ToJson(); timings.Add("RouteValues:" + timer.ElapsedMilliseconds); return(string.Format( string.Join(System.Environment.NewLine, "Action: {0} {1}", "RouteValues : {8}", "Constraints: {2}", "AttributeRouteInfo : {3}", "BoundProperties : {4}", "FilterDescriptors : {5}", "Parameters : {6}", "Properties : {7}", "Cumulative time in milliseconds to inspect and format each attribute: {9}"), displayName, a.ToString(), routeValues, constraints, attributeRouteInfo, boundProperties, filterDescriptors, parameters, properties, string.Join(", ", timings) )); }
ActionContext CreateActionContext() { var routeData = new Microsoft.AspNetCore.Routing.RouteData(); var actionDescriptor = new Microsoft.AspNetCore.Mvc.Abstractions.ActionDescriptor(); var actionContext = new ActionContext(HttpContextAccessor.HttpContext, routeData, actionDescriptor); actionContext.RouteData.Values.Add("controller", EmailViewDirectoryName); actionContext.ActionDescriptor.RouteValues.Add("controller", EmailViewDirectoryName); actionContext.ActionDescriptor.AttributeRouteInfo = new Microsoft.AspNetCore.Mvc.Routing.AttributeRouteInfo(); return(actionContext); }
private static Task ExecuteResultAsync <TResult>(this HttpContext context, TResult result) where TResult : IActionResult { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (result == null) { throw new ArgumentNullException(nameof(result)); } var executor = context.RequestServices.GetRequiredService <IActionResultExecutor <TResult> >(); var routeData = context.GetRouteData() ?? new RouteData(); var actionDescriptor = new Microsoft.AspNetCore.Mvc.Abstractions.ActionDescriptor(); var actionContext = new ActionContext(context, routeData, actionDescriptor); return(executor.ExecuteAsync(actionContext, result)); }
public static bool IsDefined(this Microsoft.AspNetCore.Mvc.Abstractions.ActionDescriptor actionDescriptor, Type attributeType, bool inherit) { if (actionDescriptor is ControllerActionDescriptor controllerActionDescriptor) { if (controllerActionDescriptor.MethodInfo.GetCustomAttribute(attributeType) == null) { if (inherit && controllerActionDescriptor.ControllerTypeInfo.GetCustomAttribute(attributeType) != null) { return(true); } } else { return(true); } } return(false); }
/// <summary> /// Creates an instance of an MVC controller from scratch /// when no existing ControllerContext is present /// </summary> /// <typeparam name="T">Type of the controller to create</typeparam> /// <returns>Controller Context for T</returns> /// <exception cref="InvalidOperationException">thrown if HttpContext not available</exception> public static T CreateController <T>(HttpContext httpContext, RouteData routeData = null) where T : Controller, new() { // create a disconnected controller instance T controller = new T(); /* * // get context wrapper from HttpContext if available * HttpContextBase wrapper = null; * if (HttpContext.Current != null) * wrapper = new HttpContextWrapper(System.Web.HttpContext.Current); * else * throw new InvalidOperationException( * "Can't create Controller Context if no active HttpContext instance is available."); */ if (routeData == null) { routeData = new RouteData(); } // add the controller routing if not existing if (!routeData.Values.ContainsKey("controller") && !routeData.Values.ContainsKey("Controller")) { routeData.Values.Add("controller", controller.GetType().Name .ToLower().Replace("controller", "")); } Microsoft.AspNetCore.Mvc.Abstractions.ActionDescriptor actionDescriptor = null; ActionContext a = new ActionContext(httpContext, routeData, actionDescriptor); var cc = new ControllerContext(a); // controller.ControllerContext = new ControllerContext(wrapper, routeData, controller); return(controller); }
public static async Task <IHtmlContent> RenderActionAsync(this HttpContext context, string action, string controller, string area, object?[]?parameters = null, ViewContext?existingViewContext = null) { if (action is null) { throw new ArgumentNullException(nameof(action)); } if (controller is null) { throw new ArgumentNullException(nameof(controller)); } HttpContext currentHttpContext = existingViewContext?.HttpContext ?? context; parameters ??= Array.Empty <object>(); // fetching required services for invocation IHttpContextFactory httpContextFactory = GetServiceOrFail <IHttpContextFactory>(currentHttpContext); HttpContext newHttpContext = httpContextFactory.Create(currentHttpContext.Features); IActionInvokerFactory actionInvokerFactory = GetServiceOrFail <IActionInvokerFactory>(newHttpContext); IActionDescriptorCollectionProvider actionSelector = GetServiceOrFail <IActionDescriptorCollectionProvider>(newHttpContext); // creating new action invocation context RouteData routeData = new RouteData(); RouteValueDictionary routeValues = new RouteValueDictionary(new { area, controller, action }); IRazorViewEngine ViewEngine = GetServiceOrFail <IRazorViewEngine>(newHttpContext); newHttpContext.Response.Body = new MemoryStream(); routeData.PushState(null, routeValues, null); Microsoft.AspNetCore.Mvc.Abstractions.ActionDescriptor actionDescriptor = actionSelector.ActionDescriptors.Items.First(i => i.RouteValues["Controller"] == controller && i.RouteValues["Action"] == action); ActionContext actionContext = new ActionContext(newHttpContext, routeData, actionDescriptor); //We're not invoking this using an invoker beacause it doesn't support as many object types as parameters. IControllerFactory cf = GetServiceOrFail <IControllerFactory>(newHttpContext); //build the controller Controller c = (Controller)cf.CreateController(new ControllerContext(actionContext)); //call the action to build the information required to fill the view ViewResult?viewResult = c.GetType()?.GetMethod(action)?.Invoke(c, parameters) as ViewResult; //Find the view the action says it uses ViewEngineResult result = ViewEngine.FindView(actionContext, viewResult?.ViewName ?? action, false); string htmlContent = string.Empty; using (StringWriter output = new StringWriter()) { HtmlHelperOptions options; if (existingViewContext != null) { options = new HtmlHelperOptions() { ClientValidationEnabled = existingViewContext.ClientValidationEnabled, Html5DateRenderingMode = existingViewContext.Html5DateRenderingMode, ValidationSummaryMessageElement = existingViewContext.ValidationSummaryMessageElement, ValidationMessageElement = existingViewContext.ValidationMessageElement }; } else { options = new HtmlHelperOptions() { ClientValidationEnabled = true, Html5DateRenderingMode = Html5DateRenderingMode.CurrentCulture, ValidationSummaryMessageElement = "validation-summary-errors", ValidationMessageElement = "validation-summary-messages" }; } ViewContext viewcontext = new ViewContext(actionContext, result.View, viewResult?.ViewData, viewResult?.TempData, output, options); await result.View.RenderAsync(viewcontext).ConfigureAwait(false); htmlContent = output.ToString(); } return(new HtmlString(htmlContent)); }
public BeforeViewPageEventData(Microsoft.AspNetCore.Mvc.Razor.IRazorPage page, Microsoft.AspNetCore.Mvc.Rendering.ViewContext viewContext, Microsoft.AspNetCore.Mvc.Abstractions.ActionDescriptor actionDescriptor, Microsoft.AspNetCore.Http.HttpContext httpContext) { }