是否需要try-catch-finally块来封装asp.net MVC控制器中的数据访问代码?

时间:2011-02-02 03:21:53

标签: asp.net-mvc

我是asp.net mvc的新手。我也没有足够的网络安全背景。我担心我在代码中所做的事情包含隐藏的安全问题。

请先看下面的代码:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult Create()
    {
        GuestBookEntry gbe = new GuestBookEntry();
        return View(gbe);
    }

    [HttpPost]
    public ActionResult Create(GuestBookEntry gbe)
    {
        if (ModelState.IsValid)
        {
            //any data access logic goes here.
            TempData["message"] = string.Format("{0} has been successfully added.", gbe.Name);
            return RedirectToAction("Confirmation");
        }
        else
            return View(gbe);
    }


    public ActionResult Confirmation()
    {
        string message = TempData["message"] as string;
        if (message != null)
        {
            return View((object)message);
        }
        else
            return RedirectToAction("Index");
    }
}

问题

  1. 是否需要将代码包装在带try-catch-finally块的控制器中?根据我的理解,没有必要,因为如果发生异常,asp.net框架会将其转发到默认的错误页面。
  2. 处理用户请求的最佳模式是什么?在上面的代码中,它是否足够好?

2 个答案:

答案 0 :(得分:3)

只有在您打算处理错误时才应使用Try catch。

答案 1 :(得分:2)

控制器类有一个OnException虚拟方法,您可以覆盖它。如果您想要做一些特别的事情,这将允许您处理控制器中的异常。如果您对asp.net重定向到错误页面没问题,那么这样做也没有错。

我不确定哪些数据访问与您的问题有关,如果您担心在异常情况下释放已分配的资源(如与数据库的活动连接),那么理想情况下该资源实现的任何类{ {1}}因此,您应该能够将其包装在IDisposable语句块中。