Skip to content

Requesting a new "samples/HelloJson" ~ to show how to make a simple [asp.net dnx] json API / server  #770

Closed
@govpack

Description

@govpack

Hi

i could use some help with

how to make a simple [asp.net dnx] json API http server in csharp

so i'm reading http://docs.asp.net/en/latest/ and looking at
https://github.com/aspnet/Home/tree/dev/samples/latest
and searching the web for some sample code showing how to write a simple JSON api/server that receives and returns json on asp.net dnx
-- but still lack a starting point for such

I have written a json api server in node, python, ps1, and had hopped to be finished writing one in C#, asp.net vnext today. But i cannot do so, because i do not know how to do three simple things in asp.net dnx ...

(1) Receive and return json strings via http
(2) Dynamically load method-X from some project.json/dnx App
(3) Dynamically run some arbitrary C#/dnx code at runtime

so i was thinking that in addition to:
samples/ConsoleApp
samples/HelloMvc
samples/HelloWeb

there also be a:

samples/HelloJson ~ to show how to make a simple json based http api on dnx

in addition to that i would like HelloJson to be able to dynamically require in or import at runtime a consistently named method from some other dnx Startup.cs / project, so that dynamically loaded method can be used to receive, processes, and asynchronously return the received json object after having done some work on it.

I have written the same json api server in a few languages, as an illustration of what i am trying to get working in csharp, i have pasted the powershell version below. As you can see it's all over and done with in less than 60 lines of code, and ideally is quicker to make than writing this post

cls
$FU=New-Object PSObject -Property @{"value"=9}
Function go{
Process {
$o = @{"rv"=-1}
$http = New-Object System.Net.HttpListener
$http.Prefixes.Add("http://127.0.0.1:1416/")

try {
$http.Start()
while ($true) {
$context = $http.GetContext()

if($context.Request.httpmethod -ne "post"){$o=@{"rv"=-2}}else{

[System.Net.HttpListenerRequest]$req  = $context.Request
$length = $req.ContentLength64
$buffer = New-Object "byte[]" $length
[void]$req.InputStream.Read($buffer,0,$length)
$js = [System.Text.Encoding]::UTF8.GetString($buffer)

try{$o=$js|ConvertFrom-Json}catch{$o=@{"rv"=-3}}


for($i=[math]::max( $o.rn , 0 ); $i -lt $o.rx.length; $i++){$fn=$o.rx[$i]
if(!$fn){break}
if($fn[0] -ne "p"){break}
Import-Module -Name "C:/PS_Modules1to5001/$fn"
$o.rn=$i
try{
$fun = $executioncontext.invokecommand.NewScriptBlock($fn)
Write-Host $fun.GetType()
& $($fn) $o
}catch{
Write-host $_.Exception.GetType().FullName; 
Write-host $_.Exception.Message; 
Write-Host "$($_.InvocationInfo.ScriptName)($($_.InvocationInfo.ScriptLineNumber)): $($_.InvocationInfo.Line)"
}
$o.e=$o.rv

}



}

$JS=$o|ConvertTo-JSON
if (!$JS) {$JS = "very bad"}
$R=$context.Response
$R.StatusCode=200
$buffer=[System.Text.Encoding]::UTF8.GetBytes($JS)
$len=$buffer.Length
$R.ContentLength64 = $len
$output = $R.OutputStream
$output.Write($buffer,0,$len)
$output.Close()
}
}finally{$http.Stop()}
}
}




"Powershell Listening on http://127.0.0.1:1416..."
go 
# where method 2...
Function p2{Param($o);$o.rv="Hello "+$o.e+" !@!"}
# would receive: 
{rx:'p2',e:'Bob'}
# and return:
{rx:['p2'],e:'Hello Bob !@!',rv:'Hello Bob !@!',ry:[],rn:0}

(i would have preferred to have the same method name in each case but couldn't quite get there in the case of powershell)

# and method 3 
Function p3{Param($o)
Write-Host "P3 SEES:"
Write-Host $o | ConvertTo-JSON
try{
$s=& $ExecutionContext.InvokeCommand.NewScriptBlock($o.e)
$o.rv=($s|Format-Table|Out-String)
#$o.rv = ($s | ConvertTo-Html -As Table -Fragment | Out-String )
}catch{$o.rv=$_.Exception.GetType().FullName+$_.Exception.Message+$_.InvocationInfo.ScriptName+$_.InvocationInfo.ScriptLineNumber+":"+$_.InvocationInfo.Line}

Write-Host "P3 LEAVES:"
Write-Host $o | ConvertTo-JSON

}

# would receive 
{rx:'p3',e:'get-PSDrive'}
# and return 
{rx:['p3'],e:'\r\nName Used (GB) Free (GB) Provider Root CurrentLocation\r\n---- --------- --------- -------- ---- ---------------\r\nAlias Alias \r\nC 144.85 9.42 FileSystem C:\\ Z\r\nCert Certificate \\ \r\nD FileSystem D:\\ \r\nE 11.97 56.89 FileSystem E:\\ \r\nEnv Environment \r\nFunction Function \r\nHKCU Registry HKEY_CURRENT_USER \r\nHKLM Registry HKEY_LOCAL_MACHINE \r\nVariable Variable \r\nWSMan WSMan \r\n\r\n\r\n',rv:'\r\nName Used (GB) Free (GB) Provider Root CurrentLocation\r\n---- --------- --------- -------- ---- ---------------\r\nAlias Alias \r\nC 144.85 9.42 FileSystem C:\\ Z\r\nCert Certificate \\ \r\nD FileSystem D:\\ \r\nE 11.97 56.89 FileSystem E:\\ \r\nEnv Environment \r\nFunction Function \r\nHKCU Registry HKEY_CURRENT_USER \r\nHKLM Registry HKEY_LOCAL_MACHINE \r\nVariable Variable \r\nWSMan WSMan \r\n\r\n\r\n',ry:[],rn:0}

Name           Used (GB)     Free (GB) Provider      Root                                             CurrentLocation
----           ---------     --------- --------      ----                                             ---------------
Alias                                  Alias                                                                         
C                 144.85          9.42 FileSystem    C:\                                                             
Cert                                   Certificate   \                                                               
D                                      FileSystem    D:\                                                             
E                  11.97         56.89 FileSystem    E:\                                                             
Env                                    Environment                                                                   
Function                               Function                                                                      
HKCU                                   Registry      HKEY_CURRENT_USER                                               
HKLM                                   Registry      HKEY_LOCAL_MACHINE                                              
Variable                               Variable                                                                      
WSMan                                  WSMan

hopefully that sort of thing [json APIs] can be done even more succinctly in asp.net vNext in C#, but i am totally unsure of what syntax to use and calls to make. I am hoping someone can whip up a "samples/HelloJson" to guide the way.

thanks

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions