我正在尝试使用c#代码在一个请求中上传图像和json,但服务器始终返回400个错误请求。使用fiddler执行相同的请求返回状态代码200. help ...
这是我的小提琴代码:
------ WebKitFormBoundary7MA4YWxkTrZu0gW Content-Disposition:form-data; name =“application / json”Content-Type:application / json
{“type”:“Personal”,“comments”:[“Lorem”,“Ipsum”]} ------ WebKitFormBoundary7MA4YWxkTrZu0gW-- Content-Disposition:form-data; NAME = “fieldNameHere”;文件名= “1111.jpg”
内容类型:image / jpeg
< @INCLUDE C:\ Users \ user \ Desktop \ New folder \ 1111.jpg @>
在c#中实现:
$scope.config = {
itemsPerPage: 10,
maxPages: 5,
currentPage: 0,
orderBy: 0,
fillLastPage: false
};
响应始终相同:
答案 0 :(得分:1)
您可以将参数作为字符串内容传递,请查看以下示例。
public async Task<JObject> ExecutePostAsync(Stream myStreem, string url, string token, string parameter1, string parameter2, string parameter3)
{
try
{
using (var content = new MultipartFormDataContent("----MyBoundary"))
{
using (var memoryStream = myStreem)
{
using (var stream = new StreamContent(memoryStream))
{
content.Add(stream, "file", Guid.NewGuid().ToString() + ".jpg");
content.Add(new StringContent(parameter1), "parameter1");
content.Add(new StringContent(parameter3), "parameter2");
content.Add(new StringContent(parameter3), "parameter3");
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
var responce = await client.PostAsync(url, content);
string contents = await responce.Content.ReadAsStringAsync();
return (JObject.Parse(contents));
}
}
}
}
}
catch (Exception ex)
{
throw ex;
}
}
在API中从FORM请求中获取数据
public async Task<IHttpActionResult> UploadFile()
{
string parameter1 = HttpContext.Current.Request.Form["parameter1"];
string parameter2 = HttpContext.Current.Request.Form["parameter2"];
string parameter3 = HttpContext.Current.Request.Form["parameter3"];
}