C# 将带有json类数据的文件以RESTful格式上载或发送到WebAPI 2到WebAPI 2不起作用
我希望使用HTTP POST将一个包含一些相关数据的文件从C#win应用程序上传到WebAPI 2.0,但请求似乎没有正确创建,但是当我尝试单独发送它们时,效果很好 以下是用于上传的Win应用程序代码:C# 将带有json类数据的文件以RESTful格式上载或发送到WebAPI 2到WebAPI 2不起作用,c#,json,rest,asp.net-web-api,C#,Json,Rest,Asp.net Web Api,我希望使用HTTP POST将一个包含一些相关数据的文件从C#win应用程序上传到WebAPI 2.0,但请求似乎没有正确创建,但是当我尝试单独发送它们时,效果很好 以下是用于上传的Win应用程序代码: public bool Upload(string url, string filePath, string localFilename, string uploadFileName) { Boolean isFileUploaded = false; HttpClient h
public bool Upload(string url, string filePath, string localFilename, string uploadFileName)
{
Boolean isFileUploaded = false;
HttpClient httpClient = new HttpClient();
var fileStream = File.Open(localFilename, FileMode.Open);
var fileInfo = new FileInfo(localFilename);
MultipartFormDataContent content = new MultipartFormDataContent();
content.Headers.Add("filePath", filePath);
content.Add(new StreamContent(fileStream), "\"file\"", string.Format("\"{0}\"", uploadFileName + fileInfo.Extension));
TestDocument td = new TestDocument();
td.Field1 = "ABC";
td.Field2 = "PQR";
string json = JsonConvert.SerializeObject(td);
var httpContent = new StringContent(json, Encoding.UTF8, "multipart/form-data");
content.Add(httpContent);
var result = httpClient.PostAsync(url, content);
return true;
}
在Api端:
[HttpPost]
public HttpResponseMessage Post([FromBody] Testdocument document)
{
HttpResponseMessage result = null;
Testdocument otd = new Testdocument();
otd = document;
var httpRequest = HttpContext.Current.Request;
if (httpRequest.Files.Count > 0)
{
var docfiles = new List<string>();
foreach (string file in httpRequest.Files)
{
var postedFile = httpRequest.Files[file];
var filePath = HttpContext.Current.Server.MapPath("~/App_Data/" + postedFile.FileName);
postedFile.SaveAs(filePath);
docfiles.Add(filePath);
}
result = Request.CreateResponse(HttpStatusCode.Created, docfiles);
}
else
{
result = Request.CreateResponse(HttpStatusCode.BadRequest);
}
return result;
}
[HttpPost]
公共httpresponsemessagepost([FromBody]Testdocument)
{
HttpResponseMessage结果=null;
Testdocument otd=新的Testdocument();
otd=文件;
var httpRequest=HttpContext.Current.Request;
如果(httpRequest.Files.Count>0)
{
var docfiles=新列表();
foreach(httpRequest.Files中的字符串文件)
{
var postedFile=httpRequest.Files[file];
var filePath=HttpContext.Current.Server.MapPath(“~/App\u Data/”+postedFile.FileName);
postedFile.SaveAs(文件路径);
添加(文件路径);
}
结果=Request.CreateResponse(HttpStatusCode.Created,docfiles);
}
其他的
{
结果=Request.CreateResponse(HttpStatusCode.BadRequest);
}
返回结果;
}
对此有什么建议吗?那么问题出在哪里?有错误吗?@tomredfern它不与Api连接,但是如果我删除以下内容:“var-httpContent=new-StringContent(json,Encoding.UTF8,“multipart/form-data”);content.Add(httpContent);“它工作正常。基本上它不起作用。所以有一个错误?是的。在winform HTTPRequest代码中。那个错误说明了什么?