简体   繁体   English

C#将Json传递给HTTP发布请求

[英]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. 我试图将Json字符串作为URL的HttpWebRequest的参数传递。 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# 我尝试遵循许多这样的示例,但没有成功: 如何使用C#在POST请求中发送json数据

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 Json参数正确序列化为

{"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. 我尝试了多种方法,但每次都以null结束。

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. 这是正确命中的方法,但是currencyCode和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 除了Nouman Bhatti的注释中建议的内容(定义服务中的金额类以及更新服务的POST方法签名以期望该对象)之外,还使用[FromBody]属性

class

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

New POST method signature 新的POST方法签名

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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