从MVC应用程序中的OnException方法路由到视图

时间:2016-03-03 15:16:21

标签: c# asp.net-mvc asp.net-mvc-routing

我正在尝试在操作中抛出异常时将应用程序重新路由到同一视图:

[HttpPost]
public EmptyResult Action(ModelClass modelObject)
{
    _facade.update(modelObject);
    return new EmptyResult();
}


protected override void OnException(ExceptionContext filterContext)
{
    if (filterContext.Exception is MyException)
    {
        var controllerName = (string)filterContext.RouteData.Values["controller"];
        var actionName = (string)filterContext.RouteData.Values["action"];
        var model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName);

        filterContext.Result = new ViewResult
        {
            ViewName = "~/Views/ViewFolder/View.cshtml",
            ViewData = new ViewDataDictionary<HandleErrorInfo>(model),
            TempData = filterContext.Controller.TempData
        };


        filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
    }
    base.OnException(filterContext);
}

我错过了什么?

1 个答案:

答案 0 :(得分:0)

视图名称按惯例映射。你不需要完整的路径。

  

结果的ViewName将具有显式的视图名称   传递给结果。在运行时,如果未指定视图名称   那么ASP.NET MVC将使用&#34; action&#34;由...指定的值   路由系统。它没有办法去猜测&#34;在单元测试中   视图名称应该是什么。

     

您可以在StackOverflow.com上找到有关此帖子的更多信息:   Unit testing my controller method results in an empty ViewName?

Function3<String, Optional<Integer>, State<Integer>, Tuple2<String, Integer>> mappingFunc =
            new Function3<String, Optional<Integer>, State<Integer>, Tuple2<String, Integer>>() {
              @Override
              public Tuple2<String, Integer> call(String word, Optional<Integer> one,
                  State<Integer> state) {
                int sum =  one.or(0) + (state.exists() ? state.get() : 0);
                Tuple2<String, Integer> output = new Tuple2<>(word, sum);
                state.update(sum);
                return output;
              }
            };

   JavaMapWithStateDStream<String, Integer, Integer, Tuple2<String, Integer>> stateDstream =
           adCounts.mapWithState(StateSpec.function(mappingFunc));

    stateDstream.print();
    stateDstream.foreachRDD(new Function<JavaRDD<Tuple2<String,Integer>>, Void>() {
        @Override
        public Void call(JavaRDD<Tuple2<String, Integer>> rdd) throws Exception {
            rdd.saveAsTextFile("/path/to/hdfs");
            return null;
        }
    });