項目中有一個通過WebApi接口上傳視頻文件的需要。之前在測試的時候,一直采用的只有8M多的文件,結果發布以后,需要上傳一個近百M的視頻文件。上傳后,直接失敗,接口沒有任何返回。通過查找IIS的網站請求日志,看到了返回413的錯誤
413錯誤解決辦法
1、修改IIS 網站的配置編輯器
在IIS管理器中,選中網站目錄,打開配置編輯器。找到下面的目錄。將 maxAllowedContentLength修改一下。默認是30000000,不到30M。這邊修改成了200M。
2、修改網站Web.config配置文件
加入下面這段配置
<?xml version="1.0" encoding="utf-8"?> <configuration> <location path="." inheritInChildApplications="false"> <system.webServer> <handlers> <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" /> </handlers> <aspNetCore processPath="dotnet" arguments=".\WebApi.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="inprocess" /> <security> <requestFiltering> <requestLimits maxAllowedContentLength="209715200" /> </requestFiltering> </security> </system.webServer> </location> </configuration>
經過這兩步的設置,這個時候再通過接口上傳,就會返回錯誤 Request body too large
這兩個步驟,因為當時都修改了,不確定是否只要設置Web.confgi文件就可以,還是都要設置。為了避免麻煩。就都設置了。
Request body too large 錯誤解決方法
1、修改Startup.cs
public void ConfigureServices(IServiceCollection services) { services.AddFxServices(); services.AddAutoMapper(); //解決文件上傳Request body too large services.Configure<FormOptions>(x => { x.MultipartBodyLengthLimit = 209_715_200;//最大200M }); }
2、修改接口方法
加上 [DisableRequestSizeLimit]
這個時候將項目重新發布部署一下,低於200M的文件就可以正常上傳了。
注意:上面的解決方法只適用於將.Net Core項目部署在IIS下。
如果是部署Linux系統下(參考其他博主的解決方法,具體沒有進行測試論證,僅供參考)
需要在 Program.cs 添加如下代碼
public static IWebHost BuildWebhost(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>() .UseKestrel(options => { options.Limits.MaxRequestBodySize = 209715200; // 200M }) .Build();