3

在我的项目中,我在这样的类中管理异常

 public class PortalBusinessExceptionManager
    :IBusinessExceptionManager
{
    public void HandleBusinessException(BusinessExceptionDto exceptionDto)
    {
        //TODO
    }
}

我的项目中有一个BaseController所有控制器都继承自它

public class BaseController : Controller
{
    public void SetNotification(string message, ExceptionType type)
    {
       //TO DO
    }
}

所以我想在HandleBusinessException方法中如何从当前控制器获取实例并SetNotification为其调用

 public void HandleBusinessException(BusinessExceptionDto exceptionDto)
{
    var controller=....???
     controller.SetNotification(); 
}
4

3 回答 3

4

从这个问题的答案中,您可以创建自己的ControllerFactory并将控制器实例放入会话中以供以后检索。

public class MyControllerFactory : DefaultControllerFactory
{
    public override IController CreateController(RequestContext requestContext, string controllerName)
    {
        var controller = base.CreateController(requestContext, controllerName);
        HttpContext.Current.Session["controllerInstance"] = controller;
        return controller;
    }
}

然后在您的 Apllication_Start 中注册它:

ControllerBuilder.Current.SetControllerFactory(new MyControllerFactory());

您可以在异常处理方法中调用该实例。

public void HandleBusinessException(BusinessExceptionDto exceptionDto)
{
     var controller= HttpContext.Current.Session["controllerInstance"] as BaseController;
     if(controller != null) 
     {
         controller.SetNotification(); 
     }
}

请注意,这是一个非常老套的解决方案(例如,会话可能会过期并且您的方法不会被调用),您最好OnException在您的方法中覆盖并在那里BaseController调用SetNotification

public class BaseController : Controller
{
    public void SetNotification(string message, ExceptionType type)
    {
       //TO DO
    }

    protected override void OnException(ExceptionContext filterContext)
    {
        SetNotification(filterContext.Exception.Message, yourExceptionType);
        base.OnException(filterContext);
    }
}
于 2013-04-04T08:16:38.137 回答
1

最好放入 de HttpContext.Items insted Session

于 2017-01-25T00:52:01.947 回答
0

不确定它是否能解决您的问题,但它可能会有所帮助:

// get current controller instance
var controller = DependencyResolver.Current.GetService<MyController>();
// pass current request context
controller.ControllerContext = new ControllerContext(Request.RequestContext, controller); 
// call method
controller.MethodName();
于 2016-08-12T09:34:16.947 回答