C# - POST 请求中的正文内容

标签 c# api asp.net-web-api

我需要在 C# 中进行一些 api 调用。我正在使用 Microsoft 的 Web API Client 来执行此操作。我成功发出了一些 POST 请求,但我不知道如何将字段“正文”添加到我的请求中。任何的想法 ? 这是我的代码:

    static HttpClient client = new HttpClient();
    public override void AwakeFromNib()
    {
        base.AwakeFromNib();
        notif_button.Activated += (sender, e) => {
        };
        tips_button.Activated += (sender, e) =>
        {
            Tip t1 = new Tip(title_tips.StringValue, pic_tips.StringValue, content_tips.StringValue, "TEST");
            client.BaseAddress = new Uri("my_url");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            CreateProductAsync(t1).Wait();
        };
    }

    static async Task<Uri> CreateProductAsync(Tip tips)
    {
        HttpResponseMessage response = await client.PostAsJsonAsync("api/add_tips", tips);
        response.EnsureSuccessStatusCode();
        return response.Headers.Location;
    }

最佳答案

第 1 步。选择派生自 HttpContent 的类型.如果你想用运行时代码写很多内容,你可以使用 StreamContent并在其上打开某种 StreamWriter。对于简短的内容,请使用 StringContent .您还可以为自定义内容派生自己的类。

第 2 步。在对 HttpClient.PostAsync 的调用中传递内容.

这是一个使用 StringContent 传递一些 JSON 的示例:

string json = JsonConvert.SerializeObject(someObject);
var httpContent = new StringContent(json, Encoding.UTF8, "application/json");
var httpResponse = await httpClient.PostAsync("http://www.foo.bar", httpContent);

另见 How do I set up HttpContent? .

关于C# - POST 请求中的正文内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46044206/

相关文章:

c# - 自定义 xmlns :a= tag in a soapresponse from WCF

c# - C# 中的字符串替换

javascript - WebApi 2.1 + Backbone.js 1.1.2 : sync everything at once

c# - 使用属性路由为 Web Api 在 View 中构造 url

asp.net-web-api - 如何确保ASP.net Web API Controller 的参数不为空?

c# - 如何在所有子域中保留身份验证 cookie?

c# - 无法从 'int' 转换为 'System.func<int>'

rest - 是否有 Google Cloud 项目 ID 的受限词列表?

api - 将youtube音频序列与本地视频一起使用

javascript - Node.js 跨域缺少必需的请求 header 错误