【发布时间】: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