Как отобразить мод ошибки с помощью настраиваемого фильтра Global Exception in. NET Core 3.1? - PullRequest
0 голосов
/ 23 апреля 2020

Я реализовал следующий глобальный пользовательский фильтр исключений:

public class ExceptionCustomFilter : IExceptionFilter
{
    private readonly IWebHostEnvironment _hostingEnvironment;
    private readonly IModelMetadataProvider _modelMetadataProvider;
    private readonly IHttpContextAccessor _httpContextAccessor;

    public ExceptionCustomFilter(
        IWebHostEnvironment hostingEnvironment,
        IModelMetadataProvider modelMetadataProvider,
        IHttpContextAccessor httpContextAccessor)
    {
        _hostingEnvironment = hostingEnvironment;
        _modelMetadataProvider = modelMetadataProvider;
        _httpContextAccessor = httpContextAccessor;
    }

    public void OnException(ExceptionContext filterContext)
    {
        //Redirect to global handler
        filterContext.Result = new ViewResult();
        {
            ViewName = "Error"
        };
        filterContext.ExceptionHandled = true;
        filterContext.HttpContext.Response.Clear();
    }
}

и добавил следующий код в мой метод запуска ConfigureServices():

services.AddControllersWithViews(options =>
{
    options.Filters.Add(typeof(ExceptionCustomFilter));
});
services.AddMvc(options =>
{
    options.EnableEndpointRouting = false;
    options.Filters.Add(typeof(ExceptionCustomFilter));
}); 

Я хотел сделать мой " Представление «Ошибка» (которое в настоящее время находится в моей папке Views> Shared ) отображается как модальное каждый раз, когда мой ExceptionFilter перехватывает любое исключение.

Мой просмотр «Error.cs html» сейчас :

// Render styles

<script type="text/javascript">
    $(function () {
        $('#modalError').modal('show');
    });
</script>

<div class="modal-dialog">
    <div class="modal-content">
        <div class="modal-header">
            <div class="error">
                <i class="icon-erro fa fa-exclamation-circle" aria-hidden="true"></i>
                <h2> Error </h2>
            </div>
        </div>

        <div class="modal-body">
            <div class="error">
                <p>
                    // content
                </p>
            </div>
        </div>
    </div>
</div>

1 Ответ

0 голосов
/ 24 апреля 2020

Обновление: мне удалось выяснить это, по-видимому, некоторые div идентификаторы отсутствовали, и я возвращал ViewResult вместо PartialViewResult ...

Вот полный код:

В моем пользовательском фильтре исключений

public void OnException(ExceptionContext filterContext)
{
    var logErroService = new LogErroService(filterContext.HttpContext);
    logErroService.Create(filterContext.Exception);
    if (IsAjaxRequest(filterContext.HttpContext.Request))
    {
        // Displays the error message as a modal
        filterContext.Result = new PartialViewResult()
        { 
            ViewName = "_ModalError"
        };
        filterContext.ExceptionHandled = true; 
        filterContext.HttpContext.Response.Clear();
    }
    else
    {
        // Displays the error message as a HTML Page
        filterContext.Result = new ViewResult()
        {
            ViewName = "_Error"
        };
        filterContext.ExceptionHandled = true;
        filterContext.HttpContext.Response.Clear();
    }
}

My _Error.cshtml view:

@{
    Layout = null;
}

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <!--Local-->
    // Import styles and scripts

    <title>Ops, an error has ocurred!</title>
</head>
<body>
    <div class="error">
        <i class="icon-erro fa fa-exclamation-circle" aria-hidden="true"></i>
        <h2>Error</h2>
    </div>
</body>
</html>

_ModalError.cshtml, который называется ONLY , когда ошибка возникает из-за AJAX запрос:

<!-- Local -->
// Import styles and scripts

<script type="text/javascript">
    $(function () {
        $('#ModalError').modal();
    });
</script>

<div class='modal fade' id='ModalError'>
    <div id='divModalErrorBody'>

        <div class="modal-dialog" role="document">
            <div class="modal-content">

                <div class="modal-body">
                    <button type="button" class="close" data-dismiss="modal">
                            <span aria-hidden="true">×</span>
                            <span class="sr-only">Exit</span>
                    </button>

                    <div class="error-modal">
                        <i class="icon-erro fa fa-exclamation-circle" aria-hidden="true"></i>
                        <h2> Error </h2>
                    </div>
                </div>

            </div>
        </div>

    </div>
</div>

...