简体   繁体   English

asp.net core,限制每个 API 调用的 MaxRequestBodySize

[英]asp.net core, limit MaxRequestBodySize for each API call

I like to set the MaxRequestBodySize for an API operation depending on a query string parameter when API operation is called.我喜欢在调用 API 操作时根据查询字符串参数为 API 操作设置 MaxRequestBodySize。

Let's say, something like that:比方说,这样的事情:

    [HttpPost("{para1}")]
    [RequestSizeLimit(...when para1 = "a" ? 500MB : 50MB)]
    public void PostIt(string para1, [FromBody] string bodyContent)
    {
        // do stuff
    }

However, with the RequestSizeLimit attribute this cannot be done, I guess somhow with the middleware it should be possible, but I have to admit, have not found any working solution so far.但是,使用 RequestSizeLimit 属性无法做到这一点,我想用中间件应该可以做到,但我不得不承认,到目前为止还没有找到任何可行的解决方案。

Is this technically even possible and how can I achieve the goal?这在技术上是否可行,我该如何实现目标?

I'm using .net 6.0我正在使用 .net 6.0

If you want to set the MaxRequestBodySize for an API operation, using RequestSizeLimit is right choice.如果要为 API 操作设置 MaxRequestBodySize,使用 RequestSizeLimit 是正确的选择。 But usually argument should be numbers.但通常参数应该是数字。 For example, this following code would allow PostIt to accept request bodies up to 30,000,000bytes.例如,以下代码将允许PostIt接受最多 30,000,000 字节的请求正文。

[HttpPost]                                     
[RequestSizeLimit(30_000_000)]                   
public void PostIt(string para1, [FromBody] string bodyContent)                        
{

I see you mentioned the middleware here, if the request is not working by an MVC action, the limit can still be modified by using the IHttpMaxRequestBodySizeFeature .我看到你在这里提到了中间件,如果请求不是通过 MVC 操作起作用,仍然可以使用IHttpMaxRequestBodySizeFeature修改限制。 For example:例如:

app.Run(async context =>                                                               
{                                   
context.Features.Get<IHttpMaxRequestBodySizeFeature>().MaxRequestBodySize = 30_000_000;

Using the middleware or not, the argument should be a number.是否使用中间件,参数应该是一个数字。 So I suggest writeing a function to finish your goal and then return a number as the argument.所以我建议编写一个函数来完成你的目标,然后返回一个数字作为参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM