我正在使用需要将图像发送到 API 方法的 C# webform 应用程序。POST 在 webform 应用程序中执行并命中 API POST 方法,但 API 方法中的 JObject 参数为 NULL,但 webform 中的 JSON 数据创建没有问题。如果我传递除图像之外的所有数据,则 JObject 不为空,这告诉我图像(字节)太大而无法传递。我尝试压缩图像但不起作用,尝试将 enctype="multipart/form-data" 作为表单的一部分,我还在网络中将 jsonSerialization maxJsonLength="2147483647" 增加到 int32.max API 应用程序和 Web 应用程序中的 .config 但这不起作用。不知道接下来要尝试什么,但会继续搜索,任何帮助将不胜感激。网络表单和 API 控制器代码发布在下面:
按钮点击代码:
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();
型号类:
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 控制器
[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
{
}
}
网络配置
jsonSerialization maxJsonLength="2147483647"