I'm adding this answer simply because I'm using an alternate solution that doesn't require overriding the System.Web.Mvc.Controller class. I add the following extension methods to the System.Web.Mvc.Controller class. The only "benefit" of this solution is that it doesn't require you to change the base class of the code generated Controller classes. Otherwise, it is functionally equivalent to the accepted answer.
public static JsonResult ToJsonResult(this Controller controller,
object target,
string contentType,
Encoding contentEncoding,
JsonRequestBehavior behavior)
{
if (target != null)
{
if (target.GetType().HasAttribute<DataContractAttribute>())
{
return new DataContractJsonResult() { ContentType = contentType, ContentEncoding = contentEncoding, JsonRequestBehavior = behavior, Data = target };
}
}
return new JsonResult() { ContentType = contentType, ContentEncoding = contentEncoding, JsonRequestBehavior = behavior, Data = target };
}
public static JsonResult ToJsonResult(this Controller controller, object target)
{
return controller.ToJsonResult(target, null, null, JsonRequestBehavior.DenyGet);
}
public static JsonResult ToJsonResult(this Controller controller, object target, string contentType)
{
return controller.ToJsonResult(target, contentType, null, JsonRequestBehavior.DenyGet);
}
public static JsonResult ToJsonResult(this Controller controller, object target, string contentType, Encoding contentEncoding)
{
return controller.ToJsonResult(target, contentType, contentEncoding, JsonRequestBehavior.DenyGet);
}
public static JsonResult ToJsonResult(this Controller controller, object target, string contentType, JsonRequestBehavior behavior)
{
return controller.ToJsonResult(target, contentType, null, behavior);
}
In my application, I override the default controller and use the JSON.NET serializer if the type has the DataContract attribute. This functionality is encapsulated in the DataContractJsonResult class, which is not included, but is modeled after the class in the accepted answer to this question.