Получение ActionContext действия от другого - PullRequest
1 голос
/ 18 апреля 2020

Могу ли я получить ActionContext или ActionDescriptor или что-то, что может описать конкретное действие c на основе имени маршрута?

Наличие следующего контроллера.

public class Ctrl : ControllerBase
{
    [HttpGet]
    public ActionResult Get() { ... }

    [HttpGet("{id}", Name = "GetUser")]
    public ActionResult Get(int id) { ... }
}

Что я хочу делать, когда вызывается «Get», чтобы иметь доступ к метаданным «GetUser», таким как глагол, параметры маршрута и т. д. c

что-то вроде

ActionContext/Description/Metadata info = somerService.Get(routeName : "GetUser")

или

ActionContext/Description/Metadata info = somerService["GetUser"];

что-то в этой идее.

Ответы [ 2 ]

2 голосов
/ 18 апреля 2020

Попробуйте это:

// Initialize via constructor dependency injection    
private readonly IActionDescriptorCollectionProvider _provider; 

var info = _provider.ActionDescriptors.Items.Where(x => x.AttributeRouteInfo.Name == "GetUser");
2 голосов
/ 18 апреля 2020

Существует пакет nuget, AspNetCore.RouteAnalyzer , который может предоставить то, что вы хотите. Он предоставляет строки для глагола HTTP, mvc area, path и invocation.

Внутренне он использует ActionDescriptorCollectionProvider для получения этой информации:

           List<RouteInformation> ret = new List<RouteInformation>();

            var routes = m_actionDescriptorCollectionProvider.ActionDescriptors.Items;
            foreach (ActionDescriptor _e in routes)
            {
                RouteInformation info = new RouteInformation();

                // Area
                if (_e.RouteValues.ContainsKey("area"))
                {
                    info.Area = _e.RouteValues["area"];
                }

                // Path and Invocation of Razor Pages
                if (_e is PageActionDescriptor)
                {
                    var e = _e as PageActionDescriptor;
                    info.Path = e.ViewEnginePath;
                    info.Invocation = e.RelativePath;
                }

                // Path of Route Attribute
                if (_e.AttributeRouteInfo != null)
                {
                    var e = _e;
                    info.Path = $"/{e.AttributeRouteInfo.Template}";
                }

                // Path and Invocation of Controller/Action
                if (_e is ControllerActionDescriptor)
                {
                    var e = _e as ControllerActionDescriptor;
                    if (info.Path == "")
                    {
                        info.Path = $"/{e.ControllerName}/{e.ActionName}";
                    }
                    info.Invocation = $"{e.ControllerName}Controller.{e.ActionName}";
                }

                // Extract HTTP Verb
                if (_e.ActionConstraints != null && _e.ActionConstraints.Select(t => t.GetType()).Contains(typeof(HttpMethodActionConstraint)))
                {
                    HttpMethodActionConstraint httpMethodAction = 
                        _e.ActionConstraints.FirstOrDefault(a => a.GetType() == typeof(HttpMethodActionConstraint)) as HttpMethodActionConstraint;

                    if(httpMethodAction != null)
                    {
                        info.HttpMethod = string.Join(",", httpMethodAction.HttpMethods);
                    }
                }

                // Special controller path
                if (info.Path == "/RouteAnalyzer_Main/ShowAllRoutes")
                {
                    info.Path = RouteAnalyzerRouteBuilderExtensions.RouteAnalyzerUrlPath;
                }

                // Additional information of invocation
                info.Invocation += $" ({_e.DisplayName})";

                // Generating List
                ret.Add(info);
            }

            // Result
            return ret;
        }
...