How to transfer parameters and upload an image at the same time as One web api?

I am using this controller:

public class uploadphotosController : ApiController { public Task<HttpResponseMessage> Post( ) { // Check if the request contains multipart/form-data. if (!Request.Content.IsMimeMultipartContent()) { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); } string root =HostingEnvironment.MapPath("~/photos");//Burdaki app data klasoru degisecek var provider = new MultipartFormDataStreamProvider(root); // Read the form data and return an async task. var task = Request.Content.ReadAsMultipartAsync(provider). ContinueWith<HttpResponseMessage>(t => { if (t.IsFaulted || t.IsCanceled) { return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, t.Exception); } // This illustrates how to get the file names. foreach (MultipartFileData file in provider.FileData) { string fileName = file.LocalFileName; string originalName = file.Headers.ContentDisposition.FileName; FileInfo file2 = new FileInfo(fileName); file2.CopyTo(Path.Combine(root, originalName.TrimStart('"').TrimEnd('"')), true); file2.Delete(); //Trace.WriteLine(file.Headers.ContentDisposition.FileName); // Trace.WriteLine("Server file path: " + file.LocalFileName); } return Request.CreateResponse(HttpStatusCode.OK); }); return task; } } 

And I use this in WebApiConfig.cs

  config.Routes.MapHttpRoute( name: "DefaultApi_uploadphotos", routeTemplate: "api/{ext}/uploadphotos/", defaults: new { controller = "uploadphotos" }); 

It works fine, but I need to upload an image with email and password at the same time. Because I want to upload an image if the user exists. In my opinion, everyone uploads a photo as a user or not. I want to send the image and some parameters, such as email and passwords, to the same website.

How can i do this?

early

+5
source share
1 answer

What worked for me:

 public async Task<HttpResponseMessage> PostFile(string a, string b) { var requestStream = await Request.Content.ReadAsStreamAsync(); ... } 

Routing:

 config.Routes.MapHttpRoute( name: "ControllerApi", routeTemplate: "/{controller}/{a}/{b}" ); 

Sending file:

 var request = (HttpWebRequest) HttpWebRequest.Create("http://host/controller/hello/world"); request.Method = "POST"; var stream = request.GetRequestStream(); var docFile = File.OpenRead(sourceFile); docFile.CopyTo(stream); docFile.Close(); stream.Close(); var response = request.GetResponse(); 
+3
source

Source: https://habr.com/ru/post/1209109/


All Articles