Upload a file using the PUT verb in ASP.Net Web Api 2

I would like to show the action of ASP.Net Web Api 2 using HTTP PUT verb to upload files. This is consistent with our REST model, because the API is a remote file system (similar to WebDAV but very simplified), so the client chooses resource names (thus, PUT is ideal and POST is not a logical choice).

The Web Api documentation describes how to upload files using multipart / form-data forms , but does not describe how to do this using PUT methods.

What would you use to test such an API (multi-line HTML forms do not allow PUT verbs)? Will the server implementation be similar to the multi-page implementation described in the web api documentation (using MultipartStreamProvider ), or should it look like this:

 [HttpPut] public async Task<HttpResponseMessage> PutFile(string resourcePath) { Stream fileContent = await this.Request.Content.ReadAsStreamAsync(); bool isNew = await this._storageManager.UploadFile(resourcePath, fileContent); if (isNew) { return this.Request.CreateResponse(HttpStatusCode.Created); } else { return this.Request.CreateResponse(HttpStatusCode.OK); } } 
+5
source share
1 answer

After several tests, it seems that the server-side code that I posted as an example is correct. Here is an example devoid of any authentication / authorization / error handling code:

 [HttpPut] [Route(@"api/storage/{*resourcePath?}")] public async Task<HttpResponseMessage> PutFile(string resourcePath = "") { // Extract data from request Stream fileContent = await this.Request.Content.ReadAsStreamAsync(); MediaTypeHeaderValue contentTypeHeader = this.Request.Content.Headers.ContentType; string contentType = contentTypeHeader != null ? contentTypeHeader.MediaType : "application/octet-stream"; // Save the file to the underlying storage bool isNew = await this._dal.SaveFile(resourcePath, contentType, fileContent); // Return appropriate HTTP status code if (isNew) { return this.Request.CreateResponse(HttpStatusCode.Created); } else { return this.Request.CreateResponse(HttpStatusCode.OK); } } 

A simple console application is enough to test it (using the Web Api client libraries):

 using (var fileContent = new FileStream(@"C:\temp\testfile.txt", FileMode.Open)) using (var client = new HttpClient()) { var content = new StreamContent(fileContent); content.Headers.ContentType = new MediaTypeHeaderValue("text/plain"); client.BaseAddress = new Uri("http://localhost:81"); HttpResponseMessage response = await client.PutAsync(@"/api/storage/testfile.txt", content); } 
+8
source

All Articles