My goal is to find a controller from it's name and area. I have successfully done this if my current httpContext
is within the same Area as the to-be-found controller. However, I cannot get my call to the ControllerFactory
to take Area into consideration. Here's my code:
public static ControllerBase GetControllerByName(this HtmlHelper htmlHelper, string controllerName)
{
IControllerFactory factory = ControllerBuilder.Current.GetControllerFactory();
IController controller = factory.CreateController(htmlHelper.ViewContext.RequestContext, controllerName);
if (controller == null)
{
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, "The IControllerFactory '{0}' did not return a controller for the name '{1}'.", factory.GetType(), controllerName));
}
return (ControllerBase)controller;
}
Since it's taking a RequestContext
as a parameter, I've added an route value of "area" to it but with no change. Is there something I can do with the requestContext to some how take area into consideration? Do I need to override the controller factory--and if so, what in particular handles Area distinction?
Update:
Here is an example of a AreaRegistration I have:
public class StoresAreaRegistration : AreaRegistration
{
public override string AreaName { get { return "Stores"; } }
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
AreaName,
AreaName + "/{controller}/{action}/{id}",
new { area = AreaName, controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}