【问题标题】:Proper way to handle exceptions in an API Controller in MVC在 MVC 中的 API 控制器中处理异常的正确方法
【发布时间】: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 文件中注册它。我有这个,但我认为我必须在每个控制器上都这样做。

标签: api model-view-controller


【解决方案1】:
    public static class WebApiConfig
    {
        /// <summary>
        /// Registers the specified configuration.
        /// </summary>
        /// <param name="config">The configuration.</param>
        public static void Register(HttpConfiguration config)
        {
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional });

            config.Filters.Add(new APICustomExceptionFilter());
        }
    }

我能够在我的 WebAPIConfig 的 Register 方法中注册一次。

这样就可以解决问题,因此我不必在我的应用程序中的每个 API 控制器上装饰它。

【讨论】:

    猜你喜欢
    • 2013-06-07
    • 1970-01-01
    • 1970-01-01
    • 2012-08-25
    • 1970-01-01
    • 2014-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多