如何在 API Post 方法 C# 中传递 Json 正文 [已关闭]

问题描述 投票:0回答:2

如何在API Post方法C#中传递Json body?
需要将以下数据传递到 API 中:

{
"intent": "CAPTURE",
"purchase_units": [
    {
        "amount": {
            "currency_code": "USD",
            "value": "10"
        }
    }
],
"application_context": {
    "return_url": "https://example.com/return",
    "cancel_url": "https://example.com/cancel"
}

}

c# asp.net-mvc post model-view-controller
2个回答
1
投票

您可以使用 StringContent 将 JSON 传递到请求正文:

// Create the request body.
HttpContent content = new StringContent(jsonBody, Encoding.UTF8, "application/json");


// Send request.
HttpResponseMessage response = await httpClient.PostAsync(url, content);

变量 jsonBody 是这样定义的(记得转义字符):


string jsonBody = @"{
       ""intent"": ""CAPTURE"",
       ""purchase_units"": [
                {
                    ""amount"": {
                        ""currency_code"": ""USD"",
                        ""value"": ""10""
                    }
                }
            ],
            ""application_context"": {
                ""return_url"": ""https://example.com/return"",
                ""cancel_url"": ""https://example.com/cancel""
            }
        }";

如果有帮助请告诉我。


0
投票

那又如何

$.ajax({
    type: "POST",
    contentType: 'application/json; charset=utf-8',
    data: JSON.stringify({your_json_object}),
    url: 'PostAction',
    ... });

然后在你的控制器中

public HttpResponseMessage PostAction(..., [FromBody] your_json_objec){
}
© www.soinside.com 2019 - 2024. All rights reserved.