I am using Asp net web form 4.5.1 and Asp net web Api and I trying to send some data and file to Web Api method,
my code is based on [http://www.asp.net/web-api/overview/working-with-http/sending-html-form-data,-part-2][1] example
but I want to send data via AJAX (jquery)
var formData = new FormData();
var opmlFile = $('#packFile')[0];
formData.append("opmlFile", opmlFile.files[0]);
formData.append("packageData", JSON.stringify(ko.mapping.toJS(this.selectedItem)));
$.ajax({
type: "POST",
url: "/api/MyController/MyMethod",
dataType: "json",
data: formData,
cache: false,
contentType: false,
processData: false,
success: function (response) {
},
failure: function (response) {
}
});
it seems like working case, but if I send file with in request my object data is not available(provider.FormData.AllKeys ). How to make it works ? of course I can send 2 request but it is seems not good for me.
public async Task<HttpResponseMessage> MyMethod()
{
// Check if the request contains multipart/form-data.
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
string root = HttpContext.Current.Server.MapPath("~/App_Data");
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)
{
Request.CreateErrorResponse(HttpStatusCode.InternalServerError, t.Exception);
}
// This illustrates how to get the file names.
foreach (MultipartFileData file in provider.FileData)
{
Trace.WriteLine(file.Headers.ContentDisposition.FileName);
Trace.WriteLine("Server file path: " + file.LocalFileName);
}
foreach (var key in provider.FormData.AllKeys)
{
foreach (var val in provider.FormData.GetValues(key))
{
Trace.WriteLine(string.Format("{0}: {1}", key, val));
}
}
return Request.CreateResponse(HttpStatusCode.OK);
});
return await task;
}