Skip to content

Instantly share code, notes, and snippets.

@yuessir
Created September 19, 2018 10:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yuessir/f85ea80abd9a260115f6b5d93676e0a5 to your computer and use it in GitHub Desktop.
Save yuessir/f85ea80abd9a260115f6b5d93676e0a5 to your computer and use it in GitHub Desktop.
Parsing Context.Request to JSON Format in Webapi .Net core
[HttpPost("TestPost")]
public ActionResult<string> TestPost()
{
string jsonText = "";
var context = HttpContextProvider.Current;
// context.Request.EnableRewind();
try
{
var formCollection = context.Request.Form;
jsonText = JsonConvert.SerializeObject(formCollection.Keys.ToDictionary(k => k, v => string.Join(",", formCollection[v])));
if (jsonText != "{}")
{
return jsonText;
}
}
catch
{ // ignored
}
try
{
var queryStringCollection = context.Request.Query;//todo :be check
jsonText = JsonConvert.SerializeObject(queryStringCollection.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.ToString()));
if (jsonText != "{}")
{
return jsonText;
}
}
catch
{ // ignored
}
try
{
//if (context.Request.Body.CanSeek)
//{
// // context.Request.Body.Seek(0, System.IO.SeekOrigin.Begin);
using (var stream = new StreamReader(context.Request.Body))
{
jsonText = stream.ReadToEnd();
if (jsonText != "{}")
{
return jsonText;
}
}
//}
}
catch
{
// ignored
}
return jsonText;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment