/* BeejBløg */

Mar 4, 2017 - 2 minute read - Comments -

ASP.Net Controller API nuggets

Write Directly to Response Stream

Stack-o basically covers this already but kinda danced around how minimal the code can really be for the basic scenario…

 1 2 3 4 5 6 7 8 9101112131415161718192021222324252627
//e.g. $.ajax(url, { procName: "", parms: {deliveryDate:"3/2/2016"}, returnParmName: "" }, ...)
public class GenericProcArgs
  public string procName { get; set; }
  //from: https://stackoverflow.com/questions/5022958/passing-dynamic-json-object-to-c-sharp-mvc-controller
  //super convenient way to receive JS object with arbitrary properties to be fed straight to proc parms
  public dynamic parms { get; set; }
  /// <summary>
  /// whether to titleCase the JSON property names (handy for feeding auto built datagrids)
  /// </summary>
  public bool titleCase { get; set; } = false;
  public string returnParmName { get; set; }

//here's the beef...
public ActionResult GetProc(GenericProcArgs args)
  Response.ContentType = "application/json";

  using (var proc = new Proc(args.procName))
      .AssignParms(args.parms as IDictionary<string, object>)
      .ExecuteJson(Response.OutputStream, args.titleCase);
  return new EmptyResult();
  • in my experience, the ContentType wasn’t even necessary but it feels like good practice
  • here i’m using a database layer represented by my own custom Proc class… which is a bundle of convenient methods wrapped around SqlCommand … in this case, it’s firing SqlCommand.ExecuteReader() and writing the results directly to the response via Newtonsoft.Json StreamWriters… i honestly haven’t done a real profile on this call stack but it feels like a nice straight shot from sql streaming through web tier transform to client
  • another nifty nugget in play here is the usage of C# Dynamic to catch arbitrary JS objects posted from the ajax client, and that Dynamic is then inherently castable to a Dictionary

Tags: WebDev

Kendo UI Nuggets Weather Wallpaper

comments powered by Disqus