I am trying to send image and its metadata (like name) via Newtonsoft.Json.Bson
to a WebApi Restful Server from C# console client.
Client Code:
public async Task SendRequestAsync(byte[] imageBytes, string fileName)
{
using (var stream = new MemoryStream())
using (var bson = new Newtonsoft.Json.Bson.BsonWriter(stream))
{
var jsonSerializer = new JsonSerializer();
var json = JObject.FromObject(new
{
name = fileName,
content = imageBytes
});
jsonSerializer.Serialize(bson, json);
var client = new HttpClient
{
BaseAddress = new Uri("http://localhost:1920")
};
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/bson"));
var byteArrayContent = new ByteArrayContent(stream.ToArray());
byteArrayContent.Headers.ContentType = new MediaTypeHeaderValue("application/bson");
var result = await client.PostAsync(
"api/Files", byteArrayContent);
try
{
HttpResponseMessage response = result.EnsureSuccessStatusCode();
Console.Out.WriteLine(response.IsSuccessStatusCode);
Console.Out.WriteLine(response.Headers);
Console.Out.WriteLine(response.Content);
Console.Out.WriteLine(response.StatusCode);
}
catch (Exception e)
{
Console.Out.WriteLine(e);
}
}
}
Server Code
// WebApi Controller
public JsonResult<object> Post([FromBody]FileModel fileModel)
{
Console.Out.WriteLine(fileModel.name);
Console.Out.WriteLine(fileModel.length);
return Json<object>(new
{
status = HttpStatusCode.OK,
length = fileModel.length,
name = fileModel.name
});
}
// Model Class
public class FileModel
{
public string name { get; set; }
public byte[] content { get; set; }
public int length { get; set; }
}
If I send an image of 28KB then server receive the image successfully. But If I try to send image of 20MB then I get following error
System.Net.Http.HttpRequestException: Response status code does not indicate success: 404 (Not Found).
at System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode()
at FileUploadConsole.Program.<SendRequestAsync>d__1.MoveNext() in c:\users\Projects\FileUploadConsole\FileUploadConsole\Program.cs:line 58
Line 58 is HttpResponseMessage response = result.EnsureSuccessStatusCode();
Why for large image its not able to find the service ?
Put this in your web.config:
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="4294967295" />
</requestFiltering>
</security>
The maxAllowedContentLength
specifies maximums content length in bytes and is represented by a uint, see reference . The value in my example is set to the greatest possible uint value (4 gb).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.