Pulse7
7/31/2017 - 8:48 PM

ActionConstaint example, Mobile action constraint

ActionConstaint example, Mobile action constraint

sealed class IsMobileAttribute : System.Attribute, IActionConstraint
    {
        public int Order => 0;
        
        //if this method return true than IndexMobile will be chosen
        //instead of more generic Index
        //because it will be more specific
        public bool Accept(ActionConstraintContext context)
        {
            return context.RouteContext.HttpContext.Request.Headers["user-agent"].Any(x=>x.Contains("Mobile"));
        }
    }
    
    
    public IActionResult Index()
        {
            return View();
        }

        [ActionName("Index")]
        [IsMobile] //this remove ambiguity
        public IActionResult IndexMobile()
        {
            return Content("The mobile index view");
        }