Created
September 19, 2018 10:50
-
-
Save yuessir/f85ea80abd9a260115f6b5d93676e0a5 to your computer and use it in GitHub Desktop.
Parsing Context.Request to JSON Format in Webapi .Net core
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[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