gpt4 book ai didi

c# - 如何在共享 View Error.cshtml 中显示异常消息?

转载 作者:太空狗 更新时间:2023-10-30 00:23:59 25 4
gpt4 key购买 nike

如果我从一个新的 MVC 5 项目开始,在 web.config 中设置 customErrors mode="on"允许共享 View 'Error.cshtml' 在我强制(引发)异常时显示,但它只显示以下内容文本...

Error.

An error occurred while processing your request.

如何将信息传递给此 View 以显示更多相关信息,例如发生了什么错误?如果我使用 Global.asax 方法,是否可以使用此 View ...

protected void Application_Error()

?

最佳答案

覆盖过滤器:

// In your App_Start folder
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new ErrorFilter());
filters.Add(new HandleErrorAttribute());
filters.Add(new SessionFilter());
}
}

// In your filters folder (create this)
public class ErrorFilter : System.Web.Mvc.HandleErrorAttribute
{
public override void OnException(System.Web.Mvc.ExceptionContext filterContext)
{
System.Exception exception = filterContext.Exception;
string controller = filterContext.RouteData.Values["controller"].ToString();;
string action = filterContext.RouteData.Values["action"].ToString();

if (filterContext.ExceptionHandled)
{
return;
}
else
{
// Determine the return type of the action
string actionName = filterContext.RouteData.Values["action"].ToString();
Type controllerType = filterContext.Controller.GetType();
var method = controllerType.GetMethod(actionName);
var returnType = method.ReturnType;

// If the action that generated the exception returns JSON
if (returnType.Equals(typeof(JsonResult)))
{
filterContext.Result = new JsonResult()
{
Data = "DATA not returned"
};
}

// If the action that generated the exception returns a view
if (returnType.Equals(typeof(ActionResult))
|| (returnType).IsSubclassOf(typeof(ActionResult)))
{
filterContext.Result = new ViewResult
{
ViewName = "Error"
};
}
}

// Make sure that we mark the exception as handled
filterContext.ExceptionHandled = true;
}
}

在“错误” View 的顶部声明模型:

@model System.Web.Mvc.HandleErrorInfo

然后像这样在页面上使用:

@if (Model != null)
{
<div>
@Model.Exception.Message
<br />
@Model.ControllerName
</div>
}

希望这对您有所帮助。

关于c# - 如何在共享 View Error.cshtml 中显示异常消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31441263/

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