使用 .NET 6 或 .NET 8 上传大文件

发布于:2025-02-11 ⋅ 阅读:(40) ⋅ 点赞:(0)

        如果您正在使用 .NET 6,并且它拒绝上传大文件,那么本文适合您。
        我分享了一些处理大文件时需要牢记的建议,以及如何根据我们的需求配置我们的服务,并提供无限制的服务。

本文与 https://blog.csdn.net/hefeng_aspnet/article/details/144497878 相同,但使用的是 .NET 8。

为了使服务支持大量文件上传,您必须修改program.cs:

builder.WebHost.UseKestrel(o => o.Limits.MaxRequestBodySize = null);

builder.Services.Configure<FormOptions>(x =>
{

x.ValueLengthLimit = int.MaxValue;

x.MultipartBodyLengthLimit = int.MaxValue;

x.MultipartBoundaryLengthLimit = int.MaxValue;

x.MultipartHeadersCountLimit = int.MaxValue;

x.MultipartHeadersLengthLimit = int.MaxValue;
});

  • Program.cs 文件如下所示:

using Microsoft.AspNetCore.Http.Features;

var builder = WebApplication.CreateBuilder(args);

//Set MaxRequestBodySize to null
builder.WebHost.UseKestrel(o => o.Limits.MaxRequestBodySize = null);

// Add services to the container.

builder.Services.AddControllers();

// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();

builder.Services.AddSwaggerGen();

//Set Values by default
builder.Services.Configure<FormOptions>(x =>
{
x.ValueLengthLimit = int.MaxValue;

x.MultipartBodyLengthLimit = int.MaxValue;

x.MultipartBoundaryLengthLimit = int.MaxValue;

x.MultipartHeadersCountLimit = int.MaxValue;

x.MultipartHeadersLengthLimit = int.MaxValue;
});

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{

app.UseSwagger();

app.UseSwaggerUI();

}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

要运行该服务: 

dotnet run

https://本地主机:7161/swagger

上传文件的端点:

通过这些改变,该服务已经支持大文件。

重要的 

考虑服务运行的资源非常重要。 

使用 .Net Core 3.1 或 .Net Core 5.0 上传大文件 UploadLargeFiles 示例代码:https://download.csdn.net/download/hefeng_aspnet/90138207

使用 .Net 6.0 或 .Net 8.0 上传大文件 UploadLargeFiles 示例代码: 

https://download.csdn.net/download/hefeng_aspnet/90138397

如果您喜欢此文章,请收藏、点赞、评论,谢谢,祝您快乐每一天。 


网站公告

今日签到

点亮在社区的每一天
去签到