Wednesday, May 1, 2013

.Net WebApi - four months later

In WCF it is easy to have one big class/service that is loaded with functions.  In WebApi it is best to limit the commands to four or five actions.

  • GET()
  • GET(id)
  • GET(id, oneMoreVar) - I don't recommend this unless it really makes sense
  • POST
  • PUT
  • DELETE
  • OPTIONS- if you want to get real fancy.
Don't try to make your own verbs unless you know all the browsers you need to support allow for custom verbs.  Internet Explorer 8 does not support custom verbs.

In one app I've recently worked on, the data was being stored as xml in sql.  I would highly recommend one WebApi controller per xml column and one WebApi controller for managing the non-xml columns.  Having a controller just for the SqlXml DML works nicely for 'PATCH' style commands, like replacing the text in an xml node vs. overwriting the whole document.

I would also recommend creating your own abstract base class for the WebApi controllers.  The base class will inherit from the built in ApiController base class.

When it comes to testing, create abstract base classes for your test classes. One for each verb.  The set up is fairly different for each verb and once the controller is initialized you are stuck with what you've got in your setup. 
 
If the controller logic is minimal and if you have a strong abstract base class for the WebApi Controllers, you may need to only test your first controller.  In my case the inherited controllers only had a few lines of code and no logic.  I could have even abstracted them away to a config based solution, but I like the option of being able to override base classes if needed.


No comments:

Post a Comment