如何传递错误消息到MVC 5中的错误视图? [英] How to pass error message to error view in MVC 5?

查看:154
本文介绍了如何传递错误消息到MVC 5中的错误视图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



Web.Config

 < customErrors mode =On>< / customErrors> 

代码更改



公共类CustomExceptionFilter:HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{

// _ logger .Error(未捕获异常,filterContext.Exception);

ViewResult view = new ViewResult();
view.ViewName =Error;
filterContext.Result = view;

//准备响应代码。
filterContext.ExceptionHandled = true;
filterContext.HttpContext.Response.Clear();
filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
}
}

Global.asax / p>

  protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);

//处理异常
GlobalFilters.Filters.Add(new CustomExceptionFilter());

var unityContainer = ModelContainer.Instance;
DependencyResolver.SetResolver(new UnityDependencyResolver(unityContainer));
}

错误查看

  @ * @ model System.Web.Mvc.HandleErrorAttribute * @ 
< div class =row>
< div class =col-sm-12>
< h1>错误< / h1>
< div class =col-sm-12>
< h2>处理您的请求时发生错误。< / h2>
< / div>
< / div>
< / div>

在我的错误视图中,我想显示异常消息。



另外,我还有一个要求显示不同的消息,以防 404错误存在

解决方案

  public class CustomExceptionFilter:HandleErrorAttribute {
public override void OnException(ExceptionContext filterContext){

var controller = filterContext.Controller as Controller;
controller.Response.StatusCode =(int)System.Net.HttpStatusCode.InternalServerError;
controller.Response.TrySkipIisCustomErrors = true;
filterContext.ExceptionHandled = true;

var controllerName =(string)filterContext.RouteData.Values [controller];
var actionName =(string)filterContext.RouteData.Values [action];
var exception = filterContext.Exception;
//需要一个模型来将异常数据传递给错误视图
var model = new HandleErrorInfo(exception,controllerName,actionName);

var view = new ViewResult();
view.ViewName =Error;
view.ViewData = new ViewDataDictionary();
view.ViewData.Model = model;

//将任何视图数据从原始控件复制到错误视图
//,以便它们可以访问。
var viewData = controller.ViewData;
if(viewData!= null&& viewData.Count> 0){
viewData.ToList()。ForEach(view.ViewData.Add);
}

//而不是这个
////filterContext.Result = view;
//允许错误视图显示在同一个URL上发生错误
view.ExecuteResult(filterContext);

//应该在视图已经被渲染以提高性能之后执行任何日志记录。
//_logger.Error(\"Unccept exception,exception);

}
}

Error.cshtml

  @model System.Web.Mvc.HandleErrorInfo 
@ {
ViewBag.Title =Error;
}
< div class =row>
< div class =col-sm-12>
< h1>错误< / h1>
< div class =col-sm-12>
< h2>处理您的请求时发生错误。< / h2>
< / div>
< div>
@ {
if(Model!= null&& Model.Exception!= null){
< h5>以下是可以传递给管理员的一些信息< / h5> ;
< h3>路径:~/@string.Format({0} / {1},Model.ControllerName,Model.ActionName)< / h3>
< h4>错误:@ Model.Exception.GetType()。Name< / h4>
if(Request.IsLocal){
< h4>消息:@ Model.Exception.Message< / h4>
< h5> @ Model.Exception.StackTrace< / h5>
}
}
}
< / div>
< / div>
< / div>

Web.Config

 < customErrors mode =Off/> 


I am working on exception handling and have written below code for the same.

Web.Config

<customErrors mode="On"></customErrors>

Code Changes

public class CustomExceptionFilter : HandleErrorAttribute
{
    public override void OnException(ExceptionContext filterContext)
    {

        //_logger.Error("Uncaught exception", filterContext.Exception);

        ViewResult view = new ViewResult();
        view.ViewName = "Error";
        filterContext.Result = view;

        // Prepare the response code.
        filterContext.ExceptionHandled = true;
        filterContext.HttpContext.Response.Clear();
        filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
    }
}

Global.asax

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);

    // To handle exceptions
    GlobalFilters.Filters.Add(new CustomExceptionFilter());

    var unityContainer = ModelContainer.Instance;
    DependencyResolver.SetResolver(new UnityDependencyResolver(unityContainer));
}

Error View

@*@model System.Web.Mvc.HandleErrorAttribute*@
<div class="row">
    <div class="col-sm-12">
        <h1>Error</h1>
        <div class="col-sm-12">
            <h2>An error occurred while processing your request.</h2>
        </div>
    </div>
</div>

In my error view, I want to show the exception message.

Also I have one more requirement to show different message in case of 404 error exists.

解决方案

public class CustomExceptionFilter : HandleErrorAttribute {
    public override void OnException(ExceptionContext filterContext) {

        var controller = filterContext.Controller as Controller;
        controller.Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError;
        controller.Response.TrySkipIisCustomErrors = true;
        filterContext.ExceptionHandled = true;

        var controllerName = (string)filterContext.RouteData.Values["controller"];
        var actionName = (string)filterContext.RouteData.Values["action"];
        var exception = filterContext.Exception;
        //need a model to pass exception data to error view
        var model = new HandleErrorInfo(exception, controllerName, actionName);

        var view = new ViewResult();
        view.ViewName = "Error";
        view.ViewData = new ViewDataDictionary();
        view.ViewData.Model = model;

        //copy any view data from original control over to error view
        //so they can be accessible.
        var viewData = controller.ViewData;
        if (viewData != null && viewData.Count > 0) {
            viewData.ToList().ForEach(view.ViewData.Add);
        }

        //Instead of this
        ////filterContext.Result = view;
        //Allow the error view to display on the same URL the error occurred
        view.ExecuteResult(filterContext);

        //should do any logging after view has already been rendered for improved performance.
        //_logger.Error("Uncaught exception", exception);

    }
}

Views/Shared/Error.cshtml

@model System.Web.Mvc.HandleErrorInfo
@{
    ViewBag.Title = "Error";
}
<div class="row">
    <div class="col-sm-12">
        <h1>Error</h1>
        <div class="col-sm-12">
            <h2>An error occurred while processing your request.</h2>
        </div>
        <div>
            @{
                if (Model != null && Model.Exception != null) {
                    <h5>Here is some information you can pass on to the administrator</h5>
                    <h3>Path: ~/@string.Format("{0}/{1}", Model.ControllerName, Model.ActionName)</h3>
                    <h4>Error: @Model.Exception.GetType().Name</h4>
                    if (Request.IsLocal) {
                        <h4>Message: @Model.Exception.Message</h4>
                        <h5>@Model.Exception.StackTrace</h5>
                    }
                }
            }
        </div>
    </div>
</div>

Web.Config

<customErrors mode="Off"/>

这篇关于如何传递错误消息到MVC 5中的错误视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆