正在使用 NLOG 进行日志记录,并且在发生日志记录的地方有单独的类@全局级别。根据要求,必须在日志记录结束后从该类重定向到“错误” View (Error.cshtml
)。
但它是一个非 Controller 类,因此不能使用像 RedirectToAction()
或简单地 return View("Error")
这样的常用方法。
有什么办法可以做到吗?我尝试了 Response.Redirect()
但没有做任何事情。
HttpContext.Current.Response.Redirect("/Help/Error",true);
Error.cshtml
是一个纯 HTML 文件,其中包含类似 There is some error ... please contact admin 它位于 Views/Shared/* 下
文件夹。
日志记录类存在于根文件夹下的单独文件夹中,例如 logging
。
在每次调用 Action 方法时,如果发生任何异常,则会自动调用记录器,它会记录日志并最终重定向到错误 View 。
最佳答案
您可以创建自己的基础 Controller 并在一个异常事件中处理异常
public class BaseController : Controller
{
protected override void OnException(ExceptionContext filterContext)
{
//Do your logging
// and redirect / return error view
filterContext.ExceptionHandled = true;
// If the exception occured in an ajax call. Send a json response back
// (you need to parse this and display to user as needed at client side)
if (filterContext.HttpContext.Request.Headers["X-Requested-With"]=="XMLHttpRequest")
{
filterContext.Result = new JsonResult
{
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
Data = new { Error = true, Message = filterContext.Exception.Message }
};
filterContext.HttpContext.Response.StatusCode = 500; // Set as needed
}
else
{
filterContext.Result = new ViewResult { ViewName = "Error.cshtml" };
//Assuming the view exists in the "~/Views/Shared" folder
}
}
}
现在对于您的其他 Controller ,继承自这个 bascontroller。
public class ProductsController : BaseController
{
public ActionResult Die()
{
throw new Exception("I lost!");
}
}
如果您想重定向(一个新的 GET 调用)到您的错误操作方法,您可以用 RedirectToRouteResult
替换 ViewResult。
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary {
{"controller", "Home"}, {"action", "Error"}
};
关于c# - 是否可以重定向到 MVC 中的非 Controller 类查看,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38947705/