使用C#将自定义对象传递到REST端点

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

我有一个休息端点,它接受包含两个属性的单个自定义对象参数。

让我们调用参数InfoParam

public class InfoParam
{
    public long LongVar { get; set; }
    public string StringVar { get; set; }
}

我的代码如下:

infoParam.LongVar = 12345678;
infoParam.StringVar = "abc"

var myRequest = (HttpWebRequest)WebRequest.Create(url);
myRequest.Method = "POST";

var content = string.Empty;

using (var theResponse = (HttpWebResponse)MyRequest.GetResponse())
{
    using (var stream = theResponse.GetResponseStream())
    {
        using (var sr = new StreamReader(stream))
        {
            content = sr.ReadToEnd();
        }
    }
}

所以我有两个值的InfoParam变量,但我不知道将其传递到REST端点的位置。

c# rest webrequest endpoint
2个回答
0
投票

您需要将对象转换为字节流,然后可以将其添加到请求流中-依次将其作为HTTP POST正文发送。这些字节的格式需要匹配服务器的期望。 REST端点通常期望这些字节类似于JSON。

// assuming you have added Newtonsoft.JSON package and added the correct using statements
using (StreamWriter writer = new StreamWriter(myRequest.GetRequestStream()) {
    string json = JsonConvert.SerializeObject(infoParam);
    writer.WriteLine(json);
    writer.Flush();
}

您可能想要设置其他各种请求参数,例如Content-Type标头。


-1
投票

您必须将其插入Content

How to: Send data by using the WebRequest class

建议改用System.Net.Http.HttpClient

发件人:POST JSON data over HTTP

// Construct the HttpClient and Uri. This endpoint is for test purposes only.
        HttpClient httpClient = new HttpClient();
        Uri uri = new Uri("https://www.contoso.com/post");

        // Construct the JSON to post.
        HttpStringContent content = new HttpStringContent(
            "{ \"firstName\": \"Eliot\" }",
            UnicodeEncoding.Utf8,
            "application/json");

        // Post the JSON and wait for a response.
        HttpResponseMessage httpResponseMessage = await httpClient.PostAsync(
            uri,
            content);

        // Make sure the post succeeded, and write out the response.
        httpResponseMessage.EnsureSuccessStatusCode();
        var httpResponseBody = await httpResponseMessage.Content.ReadAsStringAsync();
        Debug.WriteLine(httpResponseBody);
© www.soinside.com 2019 - 2024. All rights reserved.