简体   繁体   中英

How to return same view from custom ExceptionFilter in mvc 5

I am using a custom exception filer to handle the exceptions at one place. As per my application requirement, the same view will display the error(business/generic) message on top of the view, but when I use below code to show the exception it shows blank page it does not return view after error. Here I am not getting how to return same view with currently bound model.

here is my ExceptionFilter class

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);
        }
    }
}

This is my view.

@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>

This is Controller

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);
    }
}

You have to add the exception filter attribute to your controller method.

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

Have a look at this page how to create and use filter attributes: https://www.c-sharpcorner.com/article/create-user-defined-filters-in-asp-net-mvc-5-in-step-by-step-process/

Also make sure you are passing data to your view in the request, otherwise under certain setups (where no exceptions are returned to the user view and error pages aren't setup), you might get a blank page.

I hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM