Thursday, July 29, 2010

MVC 2 Notes

Some brief notes about gotcha's and good practices for ASP.Net MVC 2

  • Always use Html.AntiForgeryToken() and use the [ValidateAntiForgeryToken] attribute to ensure that it has been checked on each action

  • Add ActionFilters to handle errors against each controller for the standard error types such as that thrown from ValidateAntiForgeryToken

  • Model binders will bind anything at any time so ensure that binding policies are in place so that users can maliciously bind data

  • Use Linq-to-SQL timestamp logic to protected against concurrency patterns along with the pattern whereby a "stub" object is created with just the PK and the TS value. Then use the Attach method in Linq to do the actual update. Again trap the error and provide good options for the user to continue

  • Use T4MVC to pre-parse all magic-strings into constants and use them throughout

  • Use localised templates copied from "C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\ItemTemplates\VisualBasic\Web\MVC 2\CodeTemplates" / "C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\ItemTemplates\CSharp\Web\MVC 2\CodeTemplates" to get consistent and useful templates rather than the Microsoft default ones

  • Tick the box to allow edit-and-continue in web applications

  • Tick the box to ensure that the the views are compiled to make sure any errors are caught

  • Be sure to use HttpPost actions when performing any CRUD type actions to prevent spiders from accidentally performing actions

  • Use NUnit / Microsoft Test to perform unit testing of controllers and models

  • Use Moq / Rhino Mocks for mocking of objects for testing

  • Use Castle Windsor / NInject for inversion of control / dependency injection

  • Use areas to divide up large applications

  • Use post followed by a RedirectAction if successful to prevent the "repeated post" warning from the browser

  • To prevent ASP.Net from filtering some URLs use the following config parameter <httpRuntime relaxedUrlToFileSystemMapping="true"/>

  • Use DisplayTemplates to enable rendering of custom datatypes as well as the built-in ones

  • Keep an eye on the ASP.Net MVC Futures stuff on codeplex as it often contains code that will be included in the next major revisions of ASP.Net MVC