1

在我的自定义异常中间件中,我希望处理异常并返回具有用户友好消息的相同资源。

例如,当Account/Add抛出一个SqlException时,我返回响应,其中包含从异常中间件Account/Add存储的消息。TempData我已经完成了这些视图引擎的事情。

我为此目的找到了这个扩展方法和用法,有了这个,你可以IActionResult从中间件返回所有实现,很好的扩展。但是,我无法找到如何返回驻留在我的视图文件夹中的常规视图,例如Views/Account/Add

异常中间件

private readonly RequestDelegate _next;

public ExceptionHandler(RequestDelegate next)
{
    _next = next;
}
public async Task Invoke(HttpContext context)
{
    try
    {
        await _next.Invoke(context);
    }
    catch (Exception ex)
    {
        HandleException(context, ex);
    }
}

private void HandleException(HttpContext context, Exception exception)
{
    //handle exception, log it and other stuff...
    //....

    var result = new ViewResult
    {
        ViewName = context.Request.Path.ToString(),
    };
    //WithDanger is an extension method writes message to tempdata
    result.WithDanger("Error", exception.ToString());

    //Extension method
    context.WriteResultAsync(result);
}

这是我尝试过的,但它没有按我的预期工作,它返回一个空白页面,似乎它没有让剃刀视图引擎运行来构建我的请求页面。

我怎样才能让我的中间件ViewResult用我现有的视图正确地返回一个?

4

1 回答 1

3

有几件事不见了。为了使用相对路径返回视图,您需要修剪前导斜杠:

ViewName = context.Request.Path.ToString().TrimStart('/')

你也没有在等待WriteResultAsync电话。将其更改为类似

private TaskHandleException(HttpContext context, Exception exception)
{
    //handle exception, log it and other stuff...
    //....

    var result = new ViewResult
    {
        ViewName = context.Request.Path.ToString().TrimStart('/'),
    };
    //WithDanger is an extension method writes message to tempdata
    result.WithDanger("Error", exception.ToString());

    //Extension method
    return context.WriteResultAsync(result);
}

并确保您等待致电HandleException

public async Task Invoke(HttpContext context)
{
    try
    {
        await _next.Invoke(context);
    }
    catch (Exception ex)
    {
        await HandleException(context, ex);
    }
}

那应该工作:)

于 2018-11-06T09:48:36.167 回答