[英]Upload files Asp.NET MVC 4 - Web API - Http Put verb/method
所以我必須在asp.net 中為一個API創建一個方法,該方法通過 PUT接受2 個文件(1 個json和 1 個xml用於處理數據,而不是保存 - 因為我必須這樣做,好嗎?:)),通過fiddler發送請求。 .
現在我在 fiddler (PUT METHOD) 上發送這樣的請求:
Content-Type: multipart/form-data
Authorization: XXXXX
Host: XXXX
請求正文:
<@INCLUDE *C:\Users\ZZZZ.json*@>
<@INCLUDE *C:\Users\XXXX.xml*@>
到目前為止,這是我在控制器中嘗試過的:
[HttpPut, Route("api/Student/{studentId}/Classes/{classId}")]
public async Task<string> Put(int studentId, int classId)
{
var file = HttpContext.Current.Request.Files.Count > 0 ?
HttpContext.Current.Request.Files[0] : null;
Stream fileContent = await this.Request.Content.ReadAsStreamAsync();
MediaTypeHeaderValue contentTypeHeader = this.Request.Content.Headers.ContentType;
if (fileContent != null)
return "ok";
return "not ok";
}
到目前為止,文件沒有被上傳,也沒有出現在請求中(一切都是空的)。 我也試過“請求”變量和 HttpContext。
嘗試了完全相同的事情,但使用 POST 方法(包括邊界)並且發生了同樣的情況。
你會怎么做才能完成這項工作? 我真的必須在 xml 中發送一個 json 對象和另一個,我真的無法更改語言或在 json 中發送所有內容(因為我可以使它工作)...
PS:文件沒有定義的結構,它必須是動態的 PS2:然后你將如何嘗試讀取這些文件而不實際保存它們?
您不必使用流來讀取文件內容。 您可以嘗試使用HttpPostedFile
。
[HttpPut, Route("api/student/{studentId}/classes/{classId}")]
public async Task<string> Put(int studentId, int classId)
{
if (HttpContext.Current.Request.Files.Count == 0)
throw new HttpResponseException(new HttpResponseMessage()
{
ReasonPhrase = "Files are required",
StatusCode = HttpStatusCode.BadRequest
});
foreach (string file in HttpContext.Current.Request.Files)
{
var postedFile = HttpContext.Current.Request.Files[file];
if (!(postedFile.ContentType == "application/json" || postedFile.ContentType == "application/xml"))
{
throw new System.Web.Http.HttpResponseException(new HttpResponseMessage()
{
ReasonPhrase = "Wrong content type",
StatusCode = HttpStatusCode.BadRequest
});
}
}
return "OK";
}
郵差
我的郵遞員:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.