Exemplo n.º 1
0
        private ControllerModel CreateSemanticModel(INamedTypeSymbol symbol, Compilation compilation)
        {
            // Проверяем, что это класс-наследник ControllerBase
            var controllerBase = WellKnownTypes.ControllerBase(compilation);

            if (controllerBase == null || !symbol.InheritsFrom(controllerBase))
            {
                return(null);
            }

            var model = new ControllerModel().WithSymbol(symbol);

            // Получаем RouteAttribute для контроллера
            var controllerRoute = symbol.GetAttributes()
                                  .FirstOrDefault(a => a.AttributeClass.Equals(WellKnownTypes.RouteAttribute(compilation)));

            if (controllerRoute != null)
            {
                var prefix = controllerRoute.ConstructorArguments
                             .FirstOrDefault(a => a.Type.SpecialType == SpecialType.System_String);
                model = model.WithRoutePrefix(prefix.Value as string);
            }

            var actions = ImmutableArray <ControllerAction> .Empty.ToBuilder();

            // Собираем информацию о controller actions
            foreach (var method in symbol.GetMembers().OfType <IMethodSymbol>()
                     .Where(m => m.DeclaredAccessibility.HasFlag(Accessibility.Public)))
            {
                HttpMethod httpMethod = null;
                string     route      = null;

                // Собираем атрибуты action'а:
                foreach (var attr in method.GetAttributes())
                {
                    // 1. Http Method
                    if (attr.AttributeClass.Equals(WellKnownTypes.HttpGetAttribute(compilation)))
                    {
                        httpMethod = HttpMethod.Get;
                    }
                    else if (attr.AttributeClass.Equals(WellKnownTypes.HttpPostAttribute(compilation)))
                    {
                        httpMethod = HttpMethod.Post;
                    }
                    // 2. Route
                    else if (attr.AttributeClass.Equals(WellKnownTypes.RouteAttribute(compilation)))
                    {
                        route = attr.ConstructorArguments
                                .FirstOrDefault(a => a.Type.SpecialType == SpecialType.System_String).Value as string;
                    }
                }

                if (httpMethod != null)
                {
                    actions.Add(new ControllerAction(httpMethod, route, method));
                }
            }

            return(model.WithActions(actions.ToImmutable()));
        }