I have small data and big XML (1.5MB), which I'm trying to post to Web.Api post method, later will be saved in the database. I'm trying to post it as Multipart data content but don't know how to read. What I'm doing wrong?
Example sending data:
using (var httpClient = new HttpClient())
{
string bigXml = File.ReadAllText("XML/Big.xml");
var url = "http://localhost:16065/api/Home/Post";
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var values = new Dictionary<string, string>{
{"Alpha", "Alpha value"},
{"Beta", "Beta value"},
//{"XMLfile", bigXml}, // Invalid URI: The Uri string is too long.
};
HttpContent httpContent = new FormUrlEncodedContent(values);
StringContent stringContent = new StringContent(bigXml, System.Text.Encoding.UTF32);
MultipartContent multipartContent = new MultipartContent();
multipartContent.Add(stringContent);
multipartContent.Add(httpContent);
HttpResponseMessage response = httpClient.PostAsync(url, multipartContent).Result;
response.EnsureSuccessStatusCode();
var result = response.Content.ReadAsStringAsync().Result;
Console.WriteLine(result);
}
Receiving data in Web.Api method:
public string Post()
{
if (!Request.Content.IsMimeMultipartContent())
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
HttpRequest request = HttpContext.Current.Request;
string root = HttpContext.Current.Server.MapPath("~/App_Data");
var provider = new MultipartFormDataStreamProvider(root);
MultipartFormDataContent mpfdc = new MultipartFormDataContent();
try
{
Request.Content.ReadAsMultipartAsync(provider);
string formXML = provider.FormData["FormXML"];
string content = provider.FormData["content"];
var response = Request.CreateResponse();
response.Content = mpfdc;
response.StatusCode = HttpStatusCode.OK;
return "1";
}
catch (System.Exception e)
{
return "2";
}
}