0

how can i set minimum and maximum size for file upload in asp.net core 3? i try to find Any way to fix this On the Internet, I just found a solution to define the maximum size

2 Answers 2

1

In my opinion, if you want to check the minimum and maximum file size For file upload, I suggest you could try to create a custom middleware to check the httpcontentlength, if the http content length doesn't match the minimum and maximum size, then you could return the custom response.

More details, you could refer to below codes:

Add below middleware into the startup.cs Configure method:

Notice: I use app.usewhen to check the path, this will only work for the url path contains "api". If you want to match all the request, you could directly use app.Use.

            app.UseWhen(context =>
context.Request.Path.StartsWithSegments("/api"),
CheckRequestLengthAsync);

CheckRequestLengthAsync method:

    private void CheckRequestLengthAsync(IApplicationBuilder app)
    {
        app.Use(async (context, next) =>
        {
            if (context.Request.ContentLength <50 && context.Request.ContentLength > 5)
            {
                context.Response.StatusCode = 500;
                context.Response.ContentType = "text/html";
                await context.Response.WriteAsync("Not match the content length");
            }
            else
            {
                // Do work that doesn't write to the Response.
                await next();
                // Do other work that doesn't write to the Response.
            }


        });
    }

Result:

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

i upload file from web page to api ,and file send As shown below (Request URL: data:image/jpeg;base64)
1

Answer @brando-zhang Is write but need to Little fix

if (context.Request.ContentLength <10000 || context.Request.ContentLength > 200000)

allowed 10kb-200kb

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.