如何从mvc 5中的自定义ExceptionFilter返回相同的视图

时间:2018-05-21 09:28:41

标签: c# .net asp.net-mvc-5 exceptionfilterattribute

我正在使用自定义异常文件管理器来处理一个地方的异常。根据我的应用程序要求,相同的视图将在视图顶部显示错误(业务/通用)消息,但是当我使用下面的代码显示异常时,它显示空白页面,它在错误后不返回视图。在这里,我不知道如何使用当前绑定的模型返回相同的视图。

这是我的ExceptionFilter课程

public class AutoExceptionHandler : ActionFilterAttribute, IExceptionFilter
{
    public void OnException(ExceptionContext filterContext)
    {
        Exception e = filterContext.Exception;

        ModelStateDictionary modelState = ((Controller)filterContext.Controller).ModelState;
        filterContext.ExceptionHandled = true;
        Handle(e, modelState);
    }

    public void Handle(Exception ex, ModelStateDictionary modelState)
    {
        string message = "";
        Int32? auditLogID;
        Type typ = ex.GetType();
        if (typ == typeof(IE.Factory.Http.HttpResponseException))
        {
            message = ex.Message;
        }
        else
        {
            message = MessageChannel.Instance.GetMessageDescription("GENERIC_ERR_MSG");
        }

        //auditLogID = Logger.SaveException(ex);

        if (modelState != null)
        {
            modelState.AddModelError("", message);
        }
    }
}

这是我的观点。

@model MyApp.Model.User

@{
    ViewBag.Title = "User";
    Layout = "~/Views/Shared/_LayoutEmpty.cshtml";
}

<div>
    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()

        <div class="msg">
            <div class="@(Html.ViewData.ModelState.IsValid ? "validation-summary-valid" : "validation-summary-errors") msg-pnl"
             data-valmsg-summary="true">
                <div class="msg-body">
                    <div class="text-danger">
                        The following error(s) occurred:
                        <ul class="validation-error">
                            @foreach (var modelError in Model.SelectMany(keyValuePair => keyValuePair.Value.Errors))
                            {
                                <li>@modelError.ErrorMessage</li>
                            }
                        </ul>
                    </div>
                </div>
            </div>
        </div>

        <div>
            <div>
                @Html.LabelFor(model => model.Name, "User Name:", new { @class = "m-0 p-0" })
            </div>
            <div>
                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control-required" } })
            </div>
            <div>
                @Html.ValidationMessageFor(model => model.Name, "*", new { @class = "text-danger" })
            </div>
        </div>

        <div>
            <div>
                @Html.LabelFor(model => model.Address, "Address :", new { @class = "m-0 p-0" })
            </div>
            <div>
                @Html.EditorFor(model => model.Address, new { htmlAttributes = new { @class = "form-control-required" } })
            </div>
            <div>
                @Html.ValidationMessageFor(model => model.Address, "*", new { @class = "text-danger" })
            </div>
        </div>

        <div>
            <div >
            <input type="submit" value="Save" class="btn-submit" id="btnSave" />
            </div>
        </div>
    }
</div>

这是控制器

public class UserController : BaseController
{

    public ActionResult User()
    {
        return View();
    }

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult User(User model)
    {
        //Doing some db call that may throw error
        throw new Exception("test exception");
        return View(model);
    }
}

1 个答案:

答案 0 :(得分:0)

您必须将异常过滤器属性添加到控制器方法中。

[AutoExceptionHandler]
public ActionResult User(User model)
{
    //Doing some db call that may throw error
    throw new Exception("test exception");
    return View(model);
}

查看此页面如何创建和使用过滤器属性: https://www.c-sharpcorner.com/article/create-user-defined-filters-in-asp-net-mvc-5-in-step-by-step-process/

还要确保您在请求中将数据传递到视图,否则在某些设置下(没有异常返回到用户视图且错误页面没有设置),您可能会得到一个空白页面。< / p>

我希望这会有所帮助。