I am working on a .net core project which has an web api to upload files. I have a middleware to check file's type, length etc.
I increased all limits on startup.cs file like this;
services.Configure<FormOptions>(f =>
{
f.MultipartBodyLengthLimit = Int32.MaxValue;
f.ValueLengthLimit = Int32.MaxValue;
f.BufferBodyLengthLimit = Int64.MaxValue;
f.MultipartBoundaryLengthLimit = Int32.MaxValue;
f.MultipartHeadersLengthLimit = Int32.MaxValue;
f.MemoryBufferThreshold = Int32.MaxValue;
f.ValueCountLimit = Int32.MaxValue;
});
But somehow error still shows up.
I even tried to create attribute class for limits, but no luck.
Here is the middleware class where i am checking the files:
if (authToken != String.Empty)
{
var ctype = context.Request.ContentType;
if (!IsMultipartContentType(context.Request.ContentType))
{
await context.Response.WriteAsync("Unexpected error.");
}
var boundary = GetBoundary(context.Request.ContentType);
var reader = new MultipartReader(boundary, streamBody);
reader.BodyLengthLimit = Int32.MaxValue;
var section = await reader.ReadNextSectionAsync();
while (section != null)
{
const int chunkSize = 256;
var buffer = new byte[chunkSize];
var fileName = GetFileName(section.ContentDisposition);
var bytesRead = 0;
using (var stream = new FileStream(fileName, FileMode.Append))
{
do
{
bytesRead = await section.Body.ReadAsync(buffer, 0, buffer.Length);
stream.Write(buffer, 0, bytesRead);
} while (bytesRead < 0);
}
if (!verifyUpcomingFiles(buffer))
{
await context.Response.WriteAsync("Undefined file type detected.");
}
else
{
//context.Request.Headers.Add("isVerified","verified");
await _next(context);
context.Request.ContentType = ctype;
await _next(context);
}
section = await reader.ReadNextSectionAsync();
}
}
else
{
await context.Response.WriteAsync("You are not allowed to complete this process.");
return;
}
I have been trying to make this work for 2 days.
I almost give up. Any help any help would be appreciated.