c# - 是否可以重定向到 MVC 中的非 Controller 类查看

标签 c# asp.net-mvc

正在使用 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/

相关文章:

c# - 如何将图像和 POST 数据上传到 Azure 移动服务 ApiController 终结点?

c# - 如何使用 fiddler 或任何其他工具跟踪 HttpClient 请求?

c# - 如果我不设置明确的过期时间,默认情况下东西会在 httpcache 中保留多长时间?

c# - ASP.NET MVC C# routes.MapRoute 不工作

html - MvcHtmlString.Create() 方法不返回 Html 编码的字符串

asp.net-mvc - ASP.NET MVC自定义错误页面(StatusCode 404抛出500)

c# - 如何从工作线程/类更新GUI线程/类?

c# - 写入使用 AsciiEncoding.GetBytes 和 Convert.FromBase64String 解码的字节时 FileStream.Write 中的性能问题

c# - 如何在 .NET 的单个单元测试中修改语言环境小数点分隔符?

javascript - 使用 Javascript/JQuery 取消选中复选框