c# - 如何使用 HttpClient 将 JSON 数据发布到 Web API

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

我有以下代码,基本上它接受一个动态对象(在这种情况下是类型文件)并使用 HTTPClient 类尝试将 POST 发送到 WebAPI Controller ,我遇到的问题是 Controller 总是为我的 [FromBody] 参数上的值获取 NULL

代码

var obj = new
        {
            f = new File
            {
                Description = description,
                File64 = Convert.ToBase64String(fileContent),
                FileName = fileName,
                VersionName = versionName,
                MimeType = mimeType
            },
        }

var client = new HttpClient(signingHandler)
{
   BaseAddress = new Uri(baseURL + path) //In this case v1/document/checkin/12345
};

client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));                        

HttpResponseMessage response;
action = Uri.EscapeUriString(action);

//Obj is passed into this, currently it is of type File 
var content = new StringContent(JsonConvert.SerializeObject(obj).ToString(),
            Encoding.UTF8, "application/json");

response = client.PostAsync(action, content)).Result;
if (response.IsSuccessStatusCode)
{     
    var responseContent = response.Content;                
    string responseString = responseContent.ReadAsStringAsync().Result;
    return JsonConvert.DeserializeObject<T>(responseString);
}

Controller

[HttpPost]
[Route("v1/document/checkin/{id:int}")]
public void Checkin_V1(int id, [FromBody] File f)
{
        //DO STUFF - f has null on all of its properties
}

型号

public class File
{
    public string FileName { get; set; }
    public string VersionName { get; set; }
    public string Description { get; set; }
    public string MimeType { get; set; }
    public byte[] Bytes { get; set;}
    public string File64 { get; set; }
}

模型在 WebAPI 和客户端应用程序上共享。

任何关于失败原因的帮助将不胜感激,现在已经绕了一段时间。

最佳答案

您一开始的 obj 是不需要的。那是将 f 嵌套在另一个对象中。

var obj = new
    {
        f = new File
        {
            Description = description,
            File64 = Convert.ToBase64String(fileContent),
            FileName = fileName,
            VersionName = versionName,
            MimeType = mimeType
        },
    }

更改为

var f = new File
{
    Description = description,
    File64 = Convert.ToBase64String(fileContent),
    FileName = fileName,
    VersionName = versionName,
    MimeType = mimeType
};

然后序列化f。

关于c# - 如何使用 HttpClient 将 JSON 数据发布到 Web API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38221733/

相关文章:

c# - 如何在客户端拦截器方法AsyncUnaryCall中进行异步调用

c# - 如何使用方法调用作为参数

javascript - JSON 和引用

c# - POST HttpRequestMessage 为空

asp.net-web-api - Ninject 3 - BeginBlock() 是否会覆盖 asp.net WebAPI 中的 InRequestScope?

.net - 在 web api 中使用 odata 函数 isof

c# - 如何在不知道构建配置的情况下将 EXE 从 .net 核心应用程序的 bin 目录复制到 wwwroot?

C#.NET : Scraping dynamic (JS) websites

iOS 从文档目录中高效解析大型 JSON

ios - 通过文件或通过 json 更新 iOS 数据库?