Type-safe JSON result in ASP.NET MVC

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 });
}

Comments

Popular posts from this blog

C# Record Serialization

Versioned content in MVC

Add timestamp to photo using ImageMagick