我的目标是从控制器的名称和区域中找到控制器。如果我当前的httpContext
与待找到的控制器位于同一区域内。但是,我无法拨打电话ControllerFactory
考虑面积。这是我的代码:
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;
}
由于它需要一个RequestContext
作为参数,我向其中添加了“区域”的路线值,但没有任何更改。我可以用 requestContext 做一些事情来考虑区域吗?我是否需要覆盖控制器工厂 - 如果需要,具体是什么处理区域区分?
Update:
这是我的区域注册的示例:
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 }
);
}
}
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:注意,您必须创建一个新的RequestContext。如果您重复使用现有的,它将扰乱此请求中稍后的操作和视图的解析。
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
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)