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

时间:2016-07-06 10:24:41

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

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

代码

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);
}

控制器

[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和客户端应用程序上共享。

对于为什么会失败的任何帮助都会非常感激,现在已经在圈子里走了一段时间。

2 个答案:

答案 0 :(得分:7)

不需要你在开始时的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。

答案 1 :(得分:4)

我认为代码的这一部分存在问题

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

因为这将与您真正需要的不同而序列化。 试试这个

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