【发布时间】:2019-09-12 13:14:26
【问题描述】:
在 API 控制器的 MVC 应用程序中处理错误的“正确”方式是什么?
我已经实现了:https://www.c-sharpcorner.com/article/exception-handling-in-asp-net-web-api/
但在我们的主控制器上,我可以从 : BaseController 继承如下:
/// <summary>
/// Base Controller
/// </summary>
/// <seealso cref="Controller" />
public abstract partial class BaseController : Controller
{
/// <summary>
/// Called when an unhandled exception occurs in any action. Will log to the database.
/// </summary>
/// <param name="filterContext">Information about the current request and action.</param>
protected override void OnException(ExceptionContext filterContext)
{
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.ExceptionHandled = true;
filterContext.Result = new JsonResult
{
Data = new { success = false, errorMessage = "An error has occurred and has been logged. Please contact an administrator if the issue persists." },
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
base.OnException(filterContext);
}
}
}
我不喜欢我必须在每个 API 控制器的类的顶部添加一个属性。
有没有更好的方法或者我实现的方法可以?
【问题讨论】:
-
根据您使用的版本,这可能会有所帮助stackoverflow.com/questions/38025305/…
-
@Nkosi:谢谢。我会发布答案。我发现我可以在我的 WebApiConfig 文件中注册它。我有这个,但我认为我必须在每个控制器上都这样做。