Skip to content

Instantly share code, notes, and snippets.

@jakejscott
Created June 21, 2011 09:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jakejscott/1037528 to your computer and use it in GitHub Desktop.
Save jakejscott/1037528 to your computer and use it in GitHub Desktop.
Override asp.net mvc JsonResult with the fast ServiceStack JsonSerializer
public abstract class ApplicationController : Controller
{
protected ActionResult RespondTo(Action<FormatCollection> format) {
return new FormatResult(format);
}
protected override JsonResult Json(object data, string contentType, Encoding contentEncoding, JsonRequestBehavior behavior) {
return new ServiceStackJsonResult {
Data = data,
ContentType = contentType,
ContentEncoding = contentEncoding
};
}
}
public class ServiceStackJsonResult : JsonResult
{
public override void ExecuteResult(ControllerContext context) {
HttpResponseBase response = context.HttpContext.Response;
response.ContentType = !String.IsNullOrEmpty(ContentType) ? ContentType : "application/json";
if (ContentEncoding != null) {
response.ContentEncoding = ContentEncoding;
}
if (Data != null) {
response.Write(JsonSerializer.SerializeToString(Data));
}
}
}
@jakejscott
Copy link
Author

Oh and do away with the annoying JsonRequestBehavior B$

@yhersh
Copy link

yhersh commented Sep 23, 2011

Hi,
Didn't find any reference to Action or FormatResult class,Can you add it in order to have a complete working sample ?

Thanks

@jakejscott
Copy link
Author

Hi yhersh,

Have a look at
https://github.com/superlogical/Template/blob/master/src/Template.Website/Controllers/ApplicationController.cs

I am using RestfulRouting in that sample which makes it easy to setup Rails 3 like routing which is nicer that the asp.net mvc way of doing routes IMHO.
http://stevehodgkiss.github.com/restful-routing/

I've explained it a little bit better here:
https://github.com/superlogical/Template

Cheers
Jake

@yhersh
Copy link

yhersh commented Sep 23, 2011

Looks great,
Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment