C# 在MVC ChildActions中有处理异常的好方法吗
我似乎做了很多异常吞咽与儿童的行动C# 在MVC ChildActions中有处理异常的好方法吗,c#,asp.net-mvc,child-actions,C#,Asp.net Mvc,Child Actions,我似乎做了很多异常吞咽与儿童的行动 [ChildActionOnly] [OutputCache(Duration = 1200, VaryByParam = "key;param")] public ActionResult ChildPart(int key, string param) { try { var model = DoRiskyExceptionProneThing(key, param)
[ChildActionOnly]
[OutputCache(Duration = 1200, VaryByParam = "key;param")]
public ActionResult ChildPart(int key, string param)
{
try
{
var model = DoRiskyExceptionProneThing(key, param)
return View("_ChildPart", model);
}
catch (Exception ex)
{
// Log to elmah using a helper method
ErrorLog.LogError(ex, "Child Action Error ");
// return a pretty bit of HTML to avoid a whitescreen of death on the client
return View("_ChildActionOnlyError");
}
}
我感觉我在剪切和粘贴成堆的代码,每次剪切一个粘贴,我们都知道一只小猫被天使的眼泪淹没了
是否有更好的方法来管理子操作中的异常,从而允许屏幕的其余部分进行适当渲染?您可以基于Mvc的HandleError属性创建CustomHandleError属性,重写OneException方法,进行日志记录,并可能返回自定义视图
public override void OnException(ExceptionContext filterContext)
{
// Log to elmah using a helper method
ErrorLog.LogError(filterContext.Exception, "Oh no!");
var controllerName = (string)filterContext.RouteData.Values["controller"];
var actionName = (string)filterContext.RouteData.Values["action"];
if (!filterContext.HttpContext.IsCustomErrorEnabled)
{
filterContext.ExceptionHandled = true;
filterContext.HttpContext.Response.Clear();
filterContext.HttpContext.Response.StatusCode = 500;
filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
var model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName);
filterContext.Result = new ViewResult
{
ViewName = "_ChildActionOnlyError",
MasterName = Master,
ViewData = new ViewDataDictionary(model),
TempData = filterContext.Controller.TempData
};
return;
}
}
然后用以下逻辑装饰要启用的任何控制器和/或操作:
[ChildActionOnly]
[OutputCache(Duration = 1200, VaryByParam = "key;param")]
[CustomHandleError]
public ActionResult ChildPart(int key, string param)
{
var model = DoRiskyExceptionProneThing(key, param)
return View("_ChildPart", model);
}
你在这里发现了什么样的异常?任何异常,我都继承了一些非常难看的代码。问题是如果子操作中没有捕获异常,则整个屏幕不会呈现。我能够保持这种方式运行,并收集关于抛出异常的证据。大多数异常似乎是数据缺失和类似的事情。我会考虑在自定义动作筛选器中进行这些操作,这些过滤器可以与您的所有操作共享。因此,如何将动作方法逻辑封装在动作过滤器中?RVAN的答案使用一种类型的动作过滤器。这条线“Filter Currest.HutpCurrist.ISCuffError启用”是什么?检查?如果您有自定义错误RemoteOnly(并且您在本地访问应用程序)或Off,则此属性设置为false。这样可以防止向公众显示敏感信息。