Getting dynamic ExpandoObject to serialize to JSON as expected
Serializing ExpandoObjects
I am currently creating a JSON API for a handful of upcoming Sierra Trading Post projects. When I found myself generating JSON for a stripped-down representation of a number of domain classes, all wrapped with some metadata, I turned to
dynamic
and things have been going quite well. Unfortunately, there was a hurdle to getting the JSON to look the way I wanted.If you start playing around with serializing
ExpandoObject
to JSON, you will probably start finding a number of options. The easiest solution to find is the one that comes with .NET,JavaScriptSerializer
underSystem.Web.Script.Serialization
. It will happily serialize anExpandoObject
for you, but it probably won’t look the way you expect. Your searches will probably vary, but I found Newtonsoft’s JSON.NET, which handledExpandoObject
right out of the NuGet box. Then I stumbled on ServiceStack.Text (also “NuGettable”). While it does even weirder things than the .NET serializer withExpandoObject
s, it supposedly does them very fast.Subtleties with using Url.RouteUrl to get fully-qualified URLs
At some point I missed the Url.RouteUrl overload that took a protocol and returned an absolute URL based on the current context. It is quite handy when you are sending URLs out into the world (e.g., RSS feed link). I ended up using the less-handy overload that took an explicit host (same as the current, in this case) and passing it in. When someone pointed out the simpler overload, I did the obvious and deleted the host from the call. That didn’t quite work.
For those looking for a way to get a fully-qualified URL through the route system, the less-than-obvious answer is to call the overload for Url.RouteUrl that gets a URL with a different protocol (
Url.RouteUrl(string, object, string)
), passing inRequest.Url.Scheme
for the current protocol.Handling case-insensitive enum action method parameters in ASP.NET MVC
Using enums as action method parameters
Say you have a enum, a sorting enum in this case.
public enum SortType { NewestFirst, OldestFirst, HighestRated, MostReviews }
ASP.NET will gladly let you use that enum as an action method parameter; you can even make it an optional parameter. To make it optional by routing, you need to make it nullable for the action method function parameter in your controller and add some guarding logic (!sort.HasValue or the like).