简体   繁体   中英

C# Pass Json to HTTP Post Request

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"
    });
}

In addition to what was suggested in the comment by Nouman Bhatti -- defining the amount class in your service as well as updating your service's POST method signature to expect that object -- also use the [FromBody] attribute

class

new Amount
{
    currencyCode = "EUR",
    amount = 1234
}

New POST method signature

[HttpPost]
public JsonResult Test([FromBody]Amount amount)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM