【发布时间】:2015-06-26 18:32:37
【问题描述】:
我想将文件和 json 数据从 HttpClient 发送到 web api 服务器。
我似乎无法通过有效负载访问服务器中的 json,只能作为 json var。
public class RegulationFilesController : BaseApiController
{
public void PostFile(RegulationFileDto dto)
{
//the dto is null here
}
}
这里是客户端:
using (var client = new HttpClient())
{
using (var content = new MultipartFormDataContent())
{
client.BaseAddress = new Uri(ConfigurationManager.AppSettings["ApiHost"]);
content.Add(new StreamContent(File.OpenRead(@"C:\\Chair.png")), "Chair", "Chair.png");
var parameters = new RegulationFileDto
{
ExternalAccountId = "1234",
};
JavaScriptSerializer serializer = new JavaScriptSerializer();
content.Add(new StringContent(serializer.Serialize(parameters), Encoding.UTF8, "application/json"));
var resTask = client.PostAsync("api/RegulationFiles", content); //?ApiKey=24Option_key
resTask.Wait();
resTask.ContinueWith(async responseTask =>
{
var res = await responseTask.Result.Content.ReadAsStringAsync();
}
);
}
}
这个例子可以工作:HttpClient Multipart Form Post in C# 但只能通过表单数据而不是有效负载。
能否请您建议如何访问文件以及提交的json和文件在同一请求中?
谢谢
【问题讨论】:
标签: json file-upload asp.net-web-api