0

I make a lib that has some default controller. (e.g. HomeController,AccountController )

Then I create a asp.net core webapplicaion, and import that lib.

when I need to change action ( Home/Index ),I create a HomeController .Then run,and it throw AmbiguousMatchException.

I find a idea IActionConstraint, test project in Github

    [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
    public class ControllerNamespaceConstraintAttribute : Attribute, IActionConstraint
    {
        public int Order => 1;
        /// <inheritdoc />
        public bool Accept(ActionConstraintContext context)
        {
            return IsValidForRequest(context.RouteContext, context.CurrentCandidate.Action);
        }
        public bool IsValidForRequest(RouteContext routeContext, ActionDescriptor action)
        {
            var actionNamespace = ((ControllerActionDescriptor)action).MethodInfo.DeclaringType.Namespace;
            Console.WriteLine("IsValidForRequest:" + actionNamespace);
            Console.WriteLine("routeContext.RouteData.DataTokens:" + routeContext.RouteData.DataTokens.Count());
            if (routeContext.RouteData.DataTokens.ContainsKey("Namespace"))
            {
                var dataTokenNamespace = (string)routeContext.RouteData.DataTokens.FirstOrDefault(dt => dt.Key == "Namespace").Value;
                return dataTokenNamespace == actionNamespace;
            }
            return true;
        }
    }

.......startup.cs

            app.UseEndpoints(endpoints =>
            {
                var dataTokens = new RouteValueDictionary();
                var ns = new[] { "TestMultipleController.Controllers" };
                dataTokens["Namespaces"] = ns;
                endpoints.MapControllerRoute(name: "default", pattern: "{controller=Home}/{action=Index}/{id?}",
                      defaults: null,
                      constraints: null,
                      dataTokens: dataTokens);
            });

..... HomeController.cs

    [ControllerNamespaceConstraint]
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return Content(RouteData.DataTokens.Count.ToString());
        }
    }

but it also throw the same exception,too.

Debugger, I found it cannot get the DataTokens in IActionConstraint

then How can I do ?

2 Answers 2

1

As I understand you want the controller-action pair declared in the current project (the entry project) to override the controller-action pair declared in the class library.

This is a bit tricky and requires your certain design to handle this kind of ambiguity between at least 2 controller-action pairs (for the conventional routing). When it comes to design, it's hard to say everything in details so I assume that 2 controller-action pairs are considered as duplicates and would cause an ambiguity when selecting an action at runtime if they:

  • Have the same controller name (case-insensitive)
  • Have the same action name (case-insensitive)
  • Support one same http method (get, post, ...)

The action method's parameters don't matter (so e.g: Get will match Get(int id), ...). Actually that's the logic the default action matching would use when finding the best matched action. I'm not so sure about the other criteria if any but the point here is to show you how to resolve this ambiguity by picking the best matched action (the one defined in the current executing assembly not in the class libraries).

So the idea here is to create your custom IApplicationModelConvention. The custom convention can help you apply some custom conventions affecting the loaded controllers, actions, routing ... With that convention, we have access to all ControllerModels which each one exposes its own set of valid ActionModels. So by removing the ActionModel that you don't want, you can resolve the ambiguity issue (because there is just one remaining ActionModel).

Here is the detail:

public class DuplicateActionsRemovalApplicationModelConvention : IApplicationModelConvention
{
    public void Apply(ApplicationModel application)
    {
        var currentExecutingAsm = Assembly.GetExecutingAssembly();
        var overriddenActions = application.Controllers.GroupBy(e => e.ControllerName)
                                            //select only duplicate controllers
                                           .Where(g => g.Count() > 1)
                                           .SelectMany(g => g.SelectMany(e => e.Actions)
                                                             .GroupBy(o => o, ActionModelMatchingEqualityComparer.Instance)
                                                             //select only duplicate actions
                                                             .Where(k => k.Count() > 1)
                                                             .SelectMany(e => e.OrderByDescending(x => x.Controller.ControllerType.Assembly == currentExecutingAsm)
                                                                 //select all except the action defined in the current executing assembly
                                                                 .Skip(1)))
                                           .Select(e => (controller: e.Controller, action: e));
        //for each overridden action, just remove it from the owner controller
        //this effectively means that the removed action will be overridden
        //by the only remaining one (defined in the current executing assembly)
        foreach(var overriddenAction in overriddenActions)
        {
            overriddenAction.controller.Actions.Remove(overriddenAction.action);
        }
    }
}

Here is the custom IEqualityComparer for ActionModel used in the code above. It helps match the 2 actions by the logic we described in the beginning.

public class ActionModelMatchingEqualityComparer : IEqualityComparer<ActionModel>
{
    static readonly Lazy<ActionModelMatchingEqualityComparer> _instanceLazy =
        new Lazy<ActionModelMatchingEqualityComparer>(() => new ActionModelMatchingEqualityComparer());
    public static ActionModelMatchingEqualityComparer Instance => _instanceLazy.Value;
    public bool Equals(ActionModel x, ActionModel y)
    {
        return string.Equals(x.ActionName, y.ActionName, StringComparison.OrdinalIgnoreCase) &&                   
               x.Attributes.OfType<IActionHttpMethodProvider>().SelectMany(e => e.HttpMethods).DefaultIfEmpty("GET")
                .Intersect(y.Attributes.OfType<IActionHttpMethodProvider>().SelectMany(e => e.HttpMethods).DefaultIfEmpty("GET"), 
                           StringComparer.OrdinalIgnoreCase).Any();
               
    }

    public int GetHashCode(ActionModel obj)
    {
        return (obj.ActionName?.GetHashCode() ?? 0) ^
                obj.Attributes.OfType<IActionHttpMethodProvider>()
                   .SelectMany(e => e.HttpMethods.Select(o => o.ToLower())).Distinct()
                   .OrderBy(e => e).Aggregate(0, (c, e) => (c * 13) ^ e.GetHashCode());
    }
}

In the code above, we use the type IActionHttpMethodProvider which is implemented by all HttpMethodAttribute (e.g: HttpMethodAttribute itself, HttpPostAttribute, ...) to check if the 2 actions support at least one same http method.

Finally you can register your custom IApplicationModelConvention globally, like this (code for .net core 2.2):

//code in ConfigureServices method in Startup.cs
services.AddMvc(o => {
     //...
     o.Conventions.Add(new DuplicateActionsRemovalApplicationModelConvention());
     //...
});

Now when you run your project, all the duplicate actions in the referenced class libraries will be removed and overridden by the one (considered as matched with the overridden actions) defined in the current executing assembly. Note that this current executing assembly is also the one containing the Startup.cs (the main/entry project) because that's where you add your custom convention DuplicateActionsRemovalApplicationModelConvention

0
0

Here is another approach using IActionSelector which is simpler. When it comes to selecting some things, the other answer of mine removes the things from which we select. This approach however will not remove the things but change how we select it. So basically the 2 approaches are fairly different in the idea. I believe that this IActionSelector may be better however:

public class CustomActionSelector : ActionSelector
{
    public CustomActionSelector(IActionDescriptorCollectionProvider actionDescriptorCollectionProvider, 
        ActionConstraintCache actionConstraintCache, ILoggerFactory loggerFactory) : base(actionDescriptorCollectionProvider, actionConstraintCache, loggerFactory)
    {
    }
    protected override IReadOnlyList<ActionDescriptor> SelectBestActions(IReadOnlyList<ActionDescriptor> actions)
    {
        var executingAssembly = Assembly.GetExecutingAssembly();
        var prioritizedActions = actions.GroupBy(e => e is ControllerActionDescriptor ca ? ca.ControllerName : "")
                                        .SelectMany(g => g.Key == "" || g.Count() == 1 ? g :
                                                         g.GroupBy(e => (e as ControllerActionDescriptor).ActionName)
                                                          .SelectMany(o => o.Count() == 1 ? o :
                                                                           o.OrderByDescending(e => (e as ControllerActionDescriptor).ControllerTypeInfo.Assembly == executingAssembly)
                                                                            .Take(1))).ToList();
                                
        return base.SelectBestActions(prioritizedActions);
    }
}

You need to register the custom action selector as a singleton like this:

services.AddSingleton<IActionSelector, CustomActionSelector>();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.