You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

ASP.NET Core文件上传遇BadHttpRequestException(MinRequestBodyDataRate)求助

Solutions for MinRequestBodyDataRate Issues in ASP.NET Core File Uploads

Hey there! Let's break down your questions one by one to tackle this issue effectively:

1. Targeted MinRequestBodyDataRate Adjustment via Middleware

You're right that modifying the feature inside your Upload action won't work—Kestrel enforces the min request body rate before model binding or action execution. Instead, you can use UseWhen middleware to target only your file upload route and adjust the rate limit early in the request pipeline.

Here's a concrete example for your Startup.Configure method:

app.UseWhen(context => 
    // Match your specific upload route and HTTP method
    context.Request.Path.StartsWithSegments("/api/files/upload") && 
    context.Request.Method.Equals("POST", StringComparison.OrdinalIgnoreCase),
    appBuilder =>
    {
        appBuilder.Use(async (context, next) =>
        {
            var rateFeature = context.Features.Get<IHttpMinRequestBodyDataRateFeature>();
            if (rateFeature != null)
            {
                // Option 1: Adjust the rate limit (e.g., 240 bytes over 15 seconds)
                rateFeature.MinDataRate = new MinDataRate(
                    bytesPerSecond: 16, // 240 / 15 = 16
                    gracePeriod: TimeSpan.FromSeconds(15)
                );

                // Option 2: Completely disable the limit for this route (use cautiously)
                // rateFeature.MinDataRate = null;
            }
            await next();
        });
    });

// Make sure this comes before routing/endpoints middleware
app.UseRouting();
app.UseEndpoints(endpoints => { /* Your endpoint config */ });

This middleware checks if the request matches your upload route, then modifies the rate limit feature before Kestrel's enforcement kicks in.

2. Potential Impacts of Disabling/Adjusting the Limit

The MinRequestBodyDataRate setting exists to protect your server from Slowloris attacks—where attackers send tiny chunks of data over long periods to tie up server connections. Here's what to consider:

  • Targeted adjustment (recommended): If you only loosen the limit for your upload route, the rest of your app remains protected. A longer grace period (e.g., 15-20 seconds) gives mobile users with spotty signal enough time to finish sending file data without exposing most of your endpoints to attack risk.
  • Targeted disable: Completely turning off the limit for upload routes makes that endpoint vulnerable to Slowloris attacks. Attackers could hold open multiple connections to your server, consuming resources and blocking legitimate users.
  • Global disable: This exposes your entire application to Slowloris attacks—never do this unless you have other mitigation layers (like a reverse proxy with rate limiting) in place.

Since you already use chunked uploads, adjusting the grace period rather than disabling the limit is the safest balance.

3. Safety of Ignoring These Errors

Ignoring BadHttpRequestException instances tied to MinRequestBodyDataRate is relatively safe, but you need to be precise about which exceptions you filter out:

  • Safe filtering: Configure Exceptional to ignore only the specific subset of BadHttpRequestException where the message references "MinRequestBodyDataRate". This way, you still get alerts for other critical request errors (like invalid request formatting, truncated payloads, or other attack-related issues).
  • Risk of over-filtering: If you ignore all BadHttpRequestException, you'll miss signs of actual attacks (e.g., malformed requests designed to exploit vulnerabilities) or legitimate issues with your API.
  • Attack monitoring blind spots: Even if you filter these exceptions, keep an eye on server metrics like active connections, request duration, and upload failure rates. A sudden spike in failed uploads could indicate a Slowloris attack targeting your upload route, even if exceptions are suppressed.

Example Exceptional Filter

If you're using Exceptional's configuration to filter these errors, you might add something like this:

Exceptional.Configure(config =>
{
    config.AddFilter(exception =>
    {
        var badRequestEx = exception as BadHttpRequestException;
        return badRequestEx != null && 
               badRequestEx.Message.Contains("MinRequestBodyDataRate", StringComparison.OrdinalIgnoreCase);
    });
});

内容的提问来源于stack exchange,提问作者Nick Albrecht

火山引擎 最新活动