asp.net mvc Find Controller By Name With Area

2019-07-20 21:58发布

问题:

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 }
      );
    }
  }

回答1:

The Area and Namespaces used to locate a controller are in the RouteData of the RequestContext. They are populatd by default based off of the request you are currently serving up, if you need to change them you have to do so before calling CreateController. You may get an exception when a controller cannot be found so you'll have to account for that as well.

UPDATE: Note, you MUST create a new RequestContext. If you reuse the existing one it will mess with the resolution of actions & views later on down the line in this request.

var tempRequestContext = new RequestContext(Request.RequestContext.HttpContext, new RouteData());
tempRequestContext.RouteData.DataTokens["Area"] = "";
tempRequestContext.RouteData.DataTokens["Namespaces"] = "YourCompany.Controllers";
var controller = ControllerBuilder.Current.GetControllerFactory()
                .CreateController(tempRequestContext, "ControllerName");

if(controller != null)
{
    //TODO: Implement your logic here
}