M.A*_*zad 3 c# asp.net-mvc controller asp.net-mvc-3
在我的项目中,我在此类中管理异常
public class PortalBusinessExceptionManager
:IBusinessExceptionManager
{
public void HandleBusinessException(BusinessExceptionDto exceptionDto)
{
//TODO
}
}
Run Code Online (Sandbox Code Playgroud)
BaseController我的项目中有一个所有控制器都继承自的项目
public class BaseController : Controller
{
public void SetNotification(string message, ExceptionType type)
{
//TO DO
}
}
Run Code Online (Sandbox Code Playgroud)
所以我想要在HandleBusinessException方法中如何从当前控制器获取实例并SetNotification为其调用
public void HandleBusinessException(BusinessExceptionDto exceptionDto)
{
var controller=....???
controller.SetNotification();
}
Run Code Online (Sandbox Code Playgroud)
从这个问题的答案中,您可以创建自己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;
}
}
Run Code Online (Sandbox Code Playgroud)
然后将其注册到您的Apllication_Start中:
ControllerBuilder.Current.SetControllerFactory(new MyControllerFactory());
Run Code Online (Sandbox Code Playgroud)
然后,您可以在异常处理方法中调用该实例。
public void HandleBusinessException(BusinessExceptionDto exceptionDto)
{
var controller= HttpContext.Current.Session["controllerInstance"] as BaseController;
if(controller != null)
{
controller.SetNotification();
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,这是一个非常棘手的解决方案(例如,会话可能会过期,并且您的方法将不会被调用),您最好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);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5313 次 |
| 最近记录: |