开发者

Is a try-catch-finally block mandatory to wrap data access code in an asp.net MVC controller?

开发者 https://www.devze.com 2023-02-08 14:01 出处:网络
I am very new to asp.net mvc. I also have no enough background in web security. I am afraid what I did in my code contains hidden security issues.

I am very new to asp.net mvc. I also have no enough background in web security. I am afraid what I did in my code contains hidden security issues.

Please see my code below first:

public class HomeController : Controller
{
  开发者_JAVA百科  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");
    }
}

Question

  1. Is it necessary to wrap the code in a controller with try-catch-finally block? In my understanding, it is not necessary because if exception occurs, asp.net framework will forward it to the default error page.
  2. What is the best pattern to handle user request? In my code above, is it good enough?


Try catch should only be used if you intend on handling the error.


The controller class has an OnException virtual method that you can override. This will allow you to handle exceptions in your controller if you want to do something special. If you are fine with asp.net redirecting to an error page, then there is nothing wrong with doing that as well.

I'm not sure what data access has to do with your question, if you are concerned about releasing allocated resources in case of an exception (like an active connection to the database), then ideally whatever class has that resource implements IDisposable and therefore, you should be able to wrap it in a using statement block.

0

精彩评论

暂无评论...
验证码 换一张
取 消