Testing ASP.NET Web API Multipart Form Data File upload -
i trying use n-unit test web api application unable find proper way test file upload method. best approach test method?
web api controller:
[acceptverbs("post")] public async task<httpresponsemessage> validate() { // check if request contains multipart/form-data. if (!request.content.ismimemultipartcontent()) { return request.createerrorresponse(httpstatuscode.unsupportedmediatype,"please submit valid request"); } var provider = new multipartmemorystreamprovider(); // loads file memory later on processing try { await request.content.readasmultipartasync(provider); var resp = new httpresponsemessage(httpstatuscode.ok); foreach (var item in provider.contents) { if (item.headers.contentdisposition.filename != null) { stream stream = item.readasstreamasync().result; // stuff , return response resp.content = new stringcontent(result, encoding.utf8, "application/xml"); //text/plain "application/xml" return resp; } } return resp; } catch (system.exception e) { return request.createerrorresponse(httpstatuscode.internalservererror, e); } }
based on above comment, following example:
httpclient client = new httpclient(); multipartformdatacontent formdatacontent = new multipartformdatacontent(); formdatacontent.add(new stringcontent("hello world!"),name: "greeting"); streamcontent file1 = new streamcontent(file.openread(@"c:\images\image1.jpeg")); file1.headers.contenttype = new mediatypeheadervalue("image/jpeg"); file1.headers.contentdisposition = new contentdispositionheadervalue("form-data"); file1.headers.contentdisposition.filename = "image1.jpeg"; formdatacontent.add(file1); streamcontent file2 = new streamcontent(file.openread(@"c:\images\image2.jpeg")); file2.headers.contenttype = new mediatypeheadervalue("image/jpeg"); file2.headers.contentdisposition = new contentdispositionheadervalue("form-data"); file2.headers.contentdisposition.filename = "image1.jpeg"; formdatacontent.add(file2); httpresponsemessage response = client.postasync("http://loclhost:9095/api/fileuploads", formdatacontent).result; the request on wire like:
post http://localhost:9095/api/fileuploads http/1.1 content-type: multipart/form-data; boundary="34d56c28-919b-42ab-8462-076b400bd03f" host: localhost:9095 content-length: 486 expect: 100-continue connection: keep-alive --34d56c28-919b-42ab-8462-076b400bd03f content-type: text/plain; charset=utf-8 content-disposition: form-data; name=greeting hello world! --34d56c28-919b-42ab-8462-076b400bd03f content-type: image/jpeg content-disposition: form-data; filename=image1.jpeg ----your image here------- --34d56c28-919b-42ab-8462-076b400bd03f content-type: image/jpeg content-disposition: form-data; filename=image2.jpeg ----your image here------- --34d56c28-919b-42ab-8462-076b400bd03f--
Comments
Post a Comment