3

I'm trying to do full attribute routing, without conventional routing, and trying to tell my routes which area they belong to based on the current domain.

In convention routing, I can specify my object constraints with this as an example:

context.MapRoute(
    "MyRouteName",
    "admin/sign-in",
    new { controller="AdminController", action="SignIn" },
    new { SitePermitted = new SiteConstraint("Admin") } // <-- how do I do this exact line of code but in attribute routing
);

Where SiteConstraint inherits from IRouteConstraint. How do I do the same thing, but using attribute routing? I am looking for something like this:

[AreaName("Admin")]
[Route("admin/sign-in")]
[new SiteConstraint("Admin")]
public ActionResult SignIn(...) {...}

Where MyConstraint has a Match method that gets the current http request and if its domain is "myadmindomain.com", then Match method returns true, and MVC executes this route given that the user is on myadmindomain.com/admin/sign-in.

1 Answer 1

3

What you want to do requires the use of the class RouteFactoryAttribute, in MVC 5 inhering from that class you can use your SiteConstraint but using attribute routing. So you can have something like:

public class SiteRouteAttribute : RouteFactoryAttribute
{
     public SiteRouteAttribute (string template, string sitePermitted) : base(template) 
     {
         SitePermitted = sitePermitted;
     }

     public override RouteValueDictionary Constraints
     {
          get
            {
               var constraints = new RouteValueDictionary();
               constraints.Add("site", new SiteConstraint(SitePermitted));
               return constraints;
            }
      }

      public string SitePermitted
      {
          get;
          private set;
      }
}

Then in your controller you can have:

[SiteRoute("somepath/{somevariable}/{action=Index}", "Admin")]
public class MyController : Controller
{
    public ActionResult Index()
    {
        ....
    }
}

Take a look at Jon Galloway's post which has a workable example

Sign up to request clarification or add additional context in comments.

1 Comment

With this approach, do you know if it's possible to have one area called Apples, the other Oranges, and have an action in each area that should be caught depending on the host? Example, if the host is www.apples.com, the action that should be fired off is the one in Apples controller.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.