使用HttpClient向Web API发布JSON数据的方法

3

我有以下代码,基本上它接收一个动态对象(在这种情况下是文件类型),并使用HTTPClient类尝试向WebAPI控制器发送POST请求,我的问题是控制器总是得到我的[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);
}

控制器

[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
}

Model

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个回答

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 进行序列化。

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
        }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接