【问题标题】:Exception handling and redirecting from view component视图组件的异常处理和重定向
【发布时间】:2019-02-25 23:58:18
【问题描述】:

如何在视图组件中实现异常处理?

将我的操作方法中的逻辑包装到try/catch 块中不会捕获视图组件本身引发的任何异常,并且我不希望应用程序停止运行而不管任何错误。这就是我目前正在做的并试图完成的事情:

动作方法

public IActionResult LoadComments(int id)
{
  try
  {
    return ViewComponent("CardComments", new { id });
  }
  catch (SqlException e)
  {
    return RedirectToAction("Error", "Home");
  }
}

重申一下,这不会捕获出现在视图组件本身内部的SqlException,因此它无法重定向。

查看组件

public class CardCommentsViewComponent : ViewComponent
{
  public async Task<IViewComponentResult> InvokeAsync(int id)
  {
    try
    {
      IEnumerable<CardCommentData> comments = await DbHelper.GetCardCommentData(id);
      return View(comments);
    }
    catch (SqlException e)
    {
      //Redirect from here if possible?
    }
  }
}

我可以通过控制器的 action 方法来完成这个吗?如果没有,我如何从视图组件本身重定向?我试过研究这个问题,结果是空的。任何信息都会有所帮助。

【问题讨论】:

    标签: asp.net-core asp.net-core-mvc asp.net-core-viewcomponent


    【解决方案1】:

    您可以尝试使用HttpContextAccessor.HttpContext.Response.Redirect 重定向到另一个页面:

    public class CardCommentsViewComponent : ViewComponent
    {
    
        private readonly IHttpContextAccessor _httpContextAccessor;
        public CardCommentsViewComponent( IHttpContextAccessor httpContextAccessor)
        {
    
            _httpContextAccessor = httpContextAccessor;
        }
        public async Task<IViewComponentResult> InvokeAsync(int id)
        {
            try
            {
                IEnumerable<CardCommentData> comments = await DbHelper.GetCardCommentData(id);
                return View(comments);
            }
            catch (SqlException e)
            {
                _httpContextAccessor.HttpContext.Response.Redirect("/About");
    
                return View(new List<CardCommentData>());
            }
        }
    }
    

    在 DI 注册:

    services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
    

    但首选方法是使用全局异常处理程序/filter 来跟踪异常并重定向到相关的错误页面:

    https://docs.microsoft.com/en-us/aspnet/core/fundamentals/error-handling?view=aspnetcore-2.2

    【讨论】:

    • 好的,所以使用全局异常处理程序可以将我重定向到专用的错误页面,但是我如何记录错误,catch 块是否优先于全局异常处理程序?
    • @JessieCryer ,这是基于您的设计,您可以在每个错误页面的控制器/操作中记录错误。
    猜你喜欢
    • 2011-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多