Type-safe JSON result in ASP.NET MVC

Posted by Joe Enos on June 23, 2021 · 4 mins read
public abstract class BaseController : Controller {
protected internal JsonResult<T> Json<T>(T data) {
return Json(data, null /* contentType */, null /* contentEncoding */, JsonRequestBehavior.DenyGet);
}
protected internal JsonResult<T> Json<T>(T data, string contentType) {
return Json(data, contentType, null /* contentEncoding */, JsonRequestBehavior.DenyGet);
}
protected internal virtual JsonResult<T> Json<T>(T data, string contentType, Encoding contentEncoding) {
return Json(data, contentType, contentEncoding, JsonRequestBehavior.DenyGet);
}
protected internal JsonResult<T> Json<T>(T data, JsonRequestBehavior behavior) {
return Json(data, null /* contentType */, null /* contentEncoding */, behavior);
}
protected internal JsonResult<T> Json<T>(T data, string contentType, JsonRequestBehavior behavior) {
return Json(data, contentType, null /* contentEncoding */, behavior);
}
protected internal virtual JsonResult<T> Json<T>(T data, string contentType, Encoding contentEncoding, JsonRequestBehavior behavior) {
return new JsonResult<T> {
Data = data,
ContentType = contentType,
ContentEncoding = contentEncoding,
JsonRequestBehavior = behavior
};
}
}

public class JsonResult<T> : JsonResult { }

public class Foo { public int FooId { get; set; } }

// Type-safe result, so you can't accidentally return the wrong type.
[HttpPost]
public JsonResult<Foo> GetSomeFoo() {
return Json(new Foo { FooId = 1 });
}