Как передать большой файл с помощью WCF? wcf Выдает ошибку 413 request entity too large
При попытке передать файл размером 81кб выдает ошибку, как увеличить максимальный размер передаваемого файла?
Вот код клиента:
private void button2_Click(object sender, EventArgs e)
{
byte[] image = null;
FileStream fileStream = new FileStream(imgLoc, FileMode.Open, FileAccess.Read);
BinaryReader binaryReader = new BinaryReader(fileStream);
image = binaryReader.ReadBytes((int)fileStream.Length);
if (image != null && DataBank.CurrentUserId != 0)
{
int Loaded = server.AddImage(comboBox1.Text, comboBox2.Text, comboBox3.Text,image,DataBank.CurrentUserId);
if (Loaded == 1)
{
MessageBox.Show("Изображение успешно загружено");
}
else
{
MessageBox.Show("Ошибка");
}
}
else
{
MessageBox.Show("Вы не выбрали изображение!");
}
}
Вот код сервера:
public int AddImage(string imageTag, string imageRating, string imageDestiny, byte[] image, int CurrentUserId)
{
using (DBPhotoArchiveEntities DB = new DBPhotoArchiveEntities())
{
try
{
Images Add = new Images
{
user_id = CurrentUserId,
image = image,
tag = imageTag,
rating = imageRating,
destiny = imageDestiny,
};
DB.Images.Add(Add);
DB.SaveChanges();
return 1;
}
catch { return 0; }
}
}
Конфиг клиента:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
</startup>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IPhotoArchive" />
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:58094/PhotoArchive.svc" binding="basicHttpBinding"
bindingConfiguration="BasicHttpBinding_IPhotoArchive" contract="PhotoServer.IPhotoArchive"
name="BasicHttpBinding_IPhotoArchive" />
</client>
</system.serviceModel>
</configuration>
Конфиг сервера:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.7.2" />
<httpRuntime targetFramework="4.7.2" />
</system.web>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior>
<!--Чтобы избежать раскрытия метаданных, до развертывания задайте следующим параметрам значение "false". -->
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<!--Чтобы при сбое получать подробные сведения об исключении для отладки, задайте следующему параметру значение "true". Чтобы информация об исключении не выдавалась, задайте до развертывания значение "false". -->
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
<!--
Для просмотра корневого каталога веб-приложения во время отладки установите значение true.
Перед развертыванием установите значение false, чтобы избежать раскрытия сведений в папке веб-приложения.
-->
<directoryBrowse enabled="true" />
</system.webServer>
<connectionStrings>
<add name="DBPhotoArchiveEntities" connectionString="metadata=res://*/PhotoDB.csdl|res://*/PhotoDB.ssdl|res://*/PhotoDB.msl;provider=System.Data.SqlClient;provider connection string="data source=DESKTOP-G2ATPMP;initial catalog=DBPhotoArchive;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="mssqllocaldb" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</configuration>
Ответы (2 шт):
Автор решения: CrazyElf
→ Ссылка
Попробуйте выставить параметр maxMessageLength в конфигурации web.config сервера:
<configuration>
<system.web>
<httpRuntime maxMessageLength="409600"
executionTimeoutInSeconds="300"/>
</system.web>
</configuration>
Автор решения: Slarovv
→ Ссылка
Проблема решилась потоковой передачей. Всю информацию брал с этого сайта https://www.codeproject.com/Articles/166763/WCF-Streaming-Upload-Download-Files-Over-HTTP