异常处理和从视图组件重定向

时间:2019-02-25 23:58:19

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

我想知道如何在视图组件中实现异常处理。在try catch块中从我的action方法包装逻辑不会捕获在视图组件逻辑本身内部引发的任何异常,并且我不希望该应用程序停止运行而不会出现任何错误。这是我到目前为止正在努力完成的事情:

操作方法-

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方法完成此操作吗?如果没有,如何从视图组件本身重定向?我曾尝试研究此问题,但还是空了。任何信息都有帮助。谢谢!

1 个答案:

答案 0 :(得分:0)

您可以尝试使用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