I'm trying to pass in a Json String as a parameter for a HttpWebRequest along with a URL. The request will hit the methods fine, but every time the parameters are null. I've tried to follow many examples like this one, but with no success: How to send json data in POST request using C#
Here is the sample object that will be serialized and passed
Amount amount = new Amount
{
currencyCode = "EUR",
amount = 1234
}
string JsonParameters = amount.ToJson();
var result = Methods.ExecuteHttpPostRequestWithJson("http://localhost:51581/Home/Test", JsonParameters);
Json Parameters serializes correctly into
{"currencyCode":"EUR","amount":1234}
Here is the method I'm try to create. I've tried multiple ways but they end up being null each time.
Here is the method that will be called
public static string ExecuteHttpPostRequestWithJson(string URL, string Json)
{
string result = "";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(URL);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{;
streamWriter.Write(Json);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
return result;
}
Here is the method that gets correctly hit, but with null parameters for both currencyCode and amount.
[HttpPost]
public JsonResult Test(string currencyCode, string amount)
{
return Json(new
{
Test = "It worked"
});
}