gpt4 book ai didi

asp.net-mvc-3 - MVC覆盖OnException错误: No suitable method found to override

转载 作者:行者123 更新时间:2023-12-03 07:50:01 25 4
gpt4 key购买 nike

我试图覆盖Global.asax中的OnException来处理错误并写入日志。我不确定哪一部分是错误的,每当我重建解决方案时,都会不断收到错误“MyApp.MvcApplication.OnException(System.Web.Mvc.ExceptionContext)':找不到合适的方法来覆盖”。

这是我在Application_Start()中的代码

 protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();

WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AuthConfig.RegisterAuth();
}

这是我在OnException()中拥有的代码
protected override void OnException(ExceptionContext context)
{
Exception ex = context.Exception;

if (!string.IsNullOrEmpty(ex.Message) ||
!string.IsNullOrEmpty(ex.Source.ToString()) ||
!string.IsNullOrEmpty(ex.StackTrace))
{

WriteLog(ex.Message.ToString(), ex.StackTrace.ToString(), ex.Source.ToString(), "0");

context.Result = new ViewResult
{
ViewName = String.Format("~/ErrorPage/ErrorPage?message={0}&stack={1}&source={2}", HttpUtility.UrlEncode(ex.Message), HttpUtility.UrlEncode(ex.StackTrace), HttpUtility.UrlEncode(ex.Source))
};
}

context.ExceptionHandled = true;
}

WriteLog()函数已在其他应用程序中经过测试,我认为其中没有任何问题,我什至尝试了:
protected override void OnException(ExceptionContext context) {
Exception ex = context.Exception;

context.Result = new ViewResult
{
ViewName = "~/Shared/Error.cshtml";
};
context.ExceptionHandled = true;
}

但是没有任何作用。错误只保留在那里。

怎么会发生这种问题,我该如何解决?我读了很多有关此的教程,我认为我的拼写错误不是OnException()。

请帮忙。谢谢

最佳答案

OnException内没有任何Global.asax
您有两种方法:

创建自己的HandleErrorAttribute并在FilterConfig.cs中注册

public class HandleExceptionsAttribute : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
(...)
}
}

FilterConfig.cs:
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleExceptionsAttribute());
(...)
}

或者,如果您拥有从其继承所有 Controller 的 BaseController,则重写 OnException方法。

PS:我会选择过滤器之一。

关于asp.net-mvc-3 - MVC覆盖OnException错误: No suitable method found to override,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32635302/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com