【问题标题】:Why do my web api receive null values when posting to web API?为什么我的 Web API 在发布到 Web API 时会收到空值?
【发布时间】:2020-02-10 16:14:35
【问题描述】:

我的 Web API 在Httpclient PostAsJsonAsync 中接收到空值:

public static async Task<DefaultApiResponse<T>> PostList<T>(string url, string token, List<AddEventViewModel.Agenda> request)
    {
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", token);

        var content = JsonConvert.SerializeObject(request);

        var buffer = System.Text.Encoding.UTF8.GetBytes(content);
        var byteContent = new ByteArrayContent(buffer);
        byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");

        var httpResponse = await client.PostAsJsonAsync(url, byteContent);

        var defaultresponse = JsonConvert.DeserializeObject<DefaultApiResponse<T>>(await httpResponse.Content.ReadAsStringAsync());

        return defaultresponse;
    }

为什么?

【问题讨论】:

    标签: asp.net-mvc


    【解决方案1】:

    我会尝试以 StringContent 对象的形式发布

    var content = new StringContent(
                         JsonConvert.SerializeObject(request),
                         Encoding.UTF8,
                         "application/json");
    
    defaultresponse = await client.PostAsync(url, content);
    

    【讨论】:

    • 如果我使用 postAsync 方法,它仍然会发布空值。但是,如果我使用 postjsonAsync 方法发送包含所有内容类型标题和所有内容的数据,但列表对象为空
    • 发送前您的序列化工作正常吗?以及您的议程课程是如何构建的?
    • 是的,我调试了我的代码并将我的对象列表序列化为 json 数据,但是当它使用 postAsync 方法时,它只发送一个空值
    • 我刚刚将议程类构建为一个列表,并在同一个类文件中定义了该列表的属性。
    • 你也尝试发送而不将其转换为字节数组?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-07
    • 1970-01-01
    • 1970-01-01
    • 2020-12-23
    • 1970-01-01
    • 2021-08-22
    相关资源
    最近更新 更多