我可以优雅地通过通用try / catch在Controller中运行每个ContentResult吗?

时间:2011-02-28 20:24:02

标签: asp.net .net-4.0 asp.net-mvc-3 controller global-asax

我假设有一种优雅的方式来做到这一点,但我不知道它是什么。在我正在处理的应用程序中,我有很多返回xml的ContentResults。每个返回x​​ml的动作都会通过完全相同的try / catch块运行,我会一遍又一遍地重复自己 - 这是我所说的一个例子:

public ContentResult SomeAction()
{
    try
    {
        //some stuff here
    }
    catch(Exception ex) 
    { 
        HandleErrorMethod(ex);
    }
    return this.Content(someObject.ToXmlString(), contentReturnType);
}        

这在控制器中发生了3-4次,所以我认为有一种方法可以用属性绘制它,或者在global.asax或类似的东西中运行某种方法以防止一遍又一遍地重复自己 - 更不用说将来的代码更改了。我真的不知道在哪里看(我想这就是我要问的原因);谢谢!

2 个答案:

答案 0 :(得分:3)

我遇到了这个问题。我重写Controller.OnException方法以自己的方式处理它,因此包括记录和将用户重定向到错误页面或根据请求显示JavaScrpt错误。

您可以使用HandleError属性来处理需要它的操作。

protected override void OnException(ExceptionContext filterContext)
{

if (filterContext == null)
        return;

var ex = filterContext.Exception; //Your exception
//Now put the rest of your code that is currently in your handle error method. 
}

[HandleError]
public ContentResult SomeAction()
{
   //some stuff here
   return this.Content(someObject.ToXmlString(), contentReturnType);
}   

答案 1 :(得分:1)

我最终创建了一个新的 ActionFilterAttribute 并用它绘制了必要的操作:

public class XmlExceptionAttribute : ActionFilterAttribute, IExceptionFilter
{
    public void OnException(ExceptionContext filterContext)
    {
        if (filterContext.Exception == null) return;

        var response = filterContext.Controller.ControllerContext.HttpContext.Response;
        response.ContentType = "text/xml";
        response.Write((new Status(filterContext.Exception)).ToXmlString());
    }
}

然后,如果我在一个类上需要它,我不再需要处理任何异常处理,它会被处理:

[HttpGet]
[XmlException]
public ContentResult Logout(string sessionIdStr)
{
    // do stuff
    // throw exceptions if I need to, they will be handled
    return this.Content(status.ToXmlString(), contentReturnType);
}