I'm working with a C# webform application that needs to send an image to an API method. The POST gets executed in the webform app and it hits the API POST method, but the JObject parameter in the API method is NULL but the JSON data in the webform is created with no problem. If I pass all the data excluding the image, the JObject is not null, so that tells me the image(byte) is too big to pass. I've tried to compress the image but that doesn't work, tried enctype="multipart/form-data" as part of the form, I've also increased the jsonSerialization maxJsonLength="2147483647" to int32.max in the web.config in the API app and web app but that doesn't work. Not sure what to try next, but will keep searching, any help would be much appreciated. The webform and API controller code is posted below:
Button Click code:
HttpPostedFile _File = ImageUpload.PostedFile;
int fileSize = _File.ContentLength;
string contentType = _File.ContentType;
string fileName = _File.FileName;
byte[] bytes;
using (BinaryReader br = new BinaryReader(_File.InputStream))
{
bytes = br.ReadBytes(_File.ContentLength);
}
ImageModel _ImgModel = new ImageModel();
_ImgModel.Name = fileName;
_ImgModel.ContentType = contentType;
_ImgModel.Data = bytes;
_ImgModel.idPersonFK = 1;
string apiURL = "http://localhost:XYZZ/api/Image/InsertImage";
WebRequest request = WebRequest.Create(apiURL);
request.Method = "POST";
string jsonData = JsonConvert.SerializeObject(_ImgModel);
byte[] byteArray = Encoding.UTF8.GetBytes(jsonData);
request.ContentType = "application/json";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
using (dataStream = response.GetResponseStream())
{
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
}
response.Close();
Model Class:
public class ImageModel
{
public long ImageID { get; set; }
public string Name { get; set; }
public string ContentType { get; set; }
public byte[] Data { get; set; }
public Nullable<long> idPersonFK { get; set; }
}
API Controller
[HttpPost]
[Route("api/Image/InsertImage")]
[EnableCors(origins: "*", headers: "*", methods: "*")]
public HttpResponseMessage Insert(JObject input)
{
try
{
//Code that will insert the image but input parameter is NULL;
}
catch (Exception ex)
{
logger.Error(ex, ex.Message);
return Request.CreateResponse(HttpStatusCode.BadRequest, "");
}
finally
{
}
}
Web.Config
jsonSerialization maxJsonLength="2147483647"