I got tired of seeing actions like:
public void GetStates(string countryCode)
{
... get the states ...
string js = Context.Services.JSONSerializer.Serialize(states);
Response.ContentType = "application/json";
RenderText(js);
}
They just don’t make sense. So I spent 20 minutes adding support for return binders. Now my code looks like:
[return: JSONReturnBinder]
public State[] GetStates(string countryCode)
{
return stateRepository.FetchAllByCountry(new Country(countryCode));
}
I know, I know, the attributes associated with return looks weird, but take your complain to MS/C# team. You have to play with the cards you’re dealt.
A return binder, much like a parameter binder, is a class/attribute that implements the IReturnBinder interface, which has a single method: Bind. There you can go wild and do whatever you want with the return value. You could add to the property bag, example, or use it to figure out to where the user should be redirected (struts like), or like me, you just want to serialize some data in JSON format.
I’ve also added the ability to serialize only the properties I want:
[return: JSONReturnBinder(Properties="Id,Name")]
public State[] GetStates(string countryCode)
{
return stateRepository.FetchAllByCountry(new Country(countryCode));
}
That saves bandwidth, not to mention that I dont expose the whole objects through the wire.
The code, if you’re wondering, is on my branch playground. I’m experimenting with more things, which I will blog soon.
February 21st, 2008 at 12:55 am
That’s really cool. I’m looking forward to using that.
February 21st, 2008 at 6:22 am
Maybe JSONReturnSerializer? it’s not really binding.
we were using a delegated approach for returning JSON, and the declarative one you show here is way cooler.
cooool
February 21st, 2008 at 6:24 am
Maybe make this even more generic.. If the controller method is a function always use a ReturnBinder. You can configure a default ReturnBinder (xml/json) in the baseController / appsettings.. Additionaly you could override the default ReturnBinder with an attribute on the action (for example to set the properties like in your sample)..
February 21st, 2008 at 8:09 am
Ken, like I said, it might not be always a serializer. The attribute name is following the interface name convention.
Marco, I’d accept the suggestion if you do it through code, per controller.
February 22nd, 2008 at 8:13 am
respond_to equiv of rails?
OT: how to expose monorail as REST resource?
February 22nd, 2008 at 9:49 am
see http://svn.castleproject.org:8080/svn/castlecontrib/Castle.MonoRail.Rest/
February 23rd, 2008 at 1:11 pm
Sometime i think that you are from another planet!!!
Awesome work. Would you mind if i make MvcContrib implementation?(i am currently working on this for my blog application, so once i am done with it, i can do the same for the contrib)
February 24th, 2008 at 12:05 am
As long as you give credit where credit is due.