上传大文件的 WCF 问题,托管在 IIS 中 [英] WCF problem with uploading large file, hosted in IIS

查看:18
本文介绍了上传大文件的 WCF 问题,托管在 IIS 中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将大文件上传到 IIS 中托管的 WCF 服务.

我使用的是 Restful 和 Streaming 方法.

但我无法上传超过 64KB 的文件.

我尝试了很多更改 web.config 文件中与大小相关的元素,但未能解决问题.

这是我的代码和配置,如果有人在代码中发现任何问题以及我该如何解决,请告诉我.

运营合同

[操作契约][WebInvoke(UriTemplate = "/UploadImage/{filename}")]bool UploadImage(string filename, Stream image);

运营合同的实施

public bool UploadImage(string filename, Stream image){尝试{string strFileName = ConfigurationManager.AppSettings["UploadDrector"].ToString() + 文件名;FileStream fileStream = null;使用 (fileStream = new FileStream(strFileName, FileMode.Create, FileAccess.Write, FileShare.None)){const int bufferLen = 1024;byte[] 缓冲区 = 新字节 [bufferLen];整数计数 = 0;while ((count = image.Read(buffer, 0, bufferLen)) > 0){fileStream.Write(buffer, 0, count);}fileStream.Close();图像.关闭();}返回真;}捕获(异常前){返回假;}}

web.config

 <服务><服务名称=服务"行为配置=服务行为"><端点地址="http://localhost/WCFService1" behaviorConfiguration="web"binding="webHttpBinding" bindingConfiguration="webBinding"合同=IService"><身份><dns value="localhost"/></身份></端点><endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/></服务></服务><绑定><webHttpBinding><绑定名称="webBinding"transferMode="流媒体"maxBufferSize="2147483647" maxReceivedMessageSize="2147483647"openTimeout="00:25:00" closeTimeout="00:25:00" sendTimeout="00:25:00"receiveTimeout="00:25:00" ></binding></webHttpBinding></绑定><行为><服务行为><行为名称=服务行为"><serviceMetadata httpGetEnabled="true"/><serviceDebug includeExceptionDetailInFaults="false"/></行为></serviceBehaviors></行为></system.serviceModel>

服务托管在 IIS 中

客户端代码(控制台应用程序)

private static void UploadImage(){string filePath = @"F:\Sharath\TestImage\TextFiles\SampleText2.txt";字符串文件名 = Path.GetFileName(filePath);string url = "http://localhost/WCFService1/Service.svc/";HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url + "UploadImage/" + filename);request.Accept = "text/xml";request.Method = "POST";request.ContentType = "txt/plain";FileStream fst = File.Open(filePath, FileMode.Open);长 imgLn = fst.Length;fst.Close();request.ContentLength = imgLn;使用 (Stream fileStream = File.OpenRead(filePath))使用 (Stream requestStream = request.GetRequestStream()){int bufferSize = 1024;字节[]缓冲区=新字节[缓冲区大小];int byteCount = 0;while ((byteCount = fileStream.Read(buffer, 0, bufferSize)) > 0){requestStream.Write(buffer, 0, byteCount);}}字符串结果;使用 (WebResponse 响应 = request.GetResponse())使用 (StreamReader reader = new StreamReader(response.GetResponseStream())){结果 = reader.ReadToEnd();}Console.WriteLine(result);}

使用这么多代码,我可以上传 64KB 的文件,但是当我尝试上传大小超过 64KB 的文件时,出现如下错误

<块引用>

远程服务器返回错误:(400) Bad Request

<小时>

我按照你说的做了,但我仍然遇到同样的问题,这就是我的配置现在的样子,你能告诉我这里还缺少什么

<服务名称=服务"行为配置=服务行为"><端点地址="http://localhost/WCFService1" behaviorConfiguration="web"binding="webHttpBinding" bindingConfiguration="webBinding"合同=IService"><身份><dns value="localhost"/></身份></端点><endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/></服务></服务><绑定><webHttpBinding><binding transferMode="流媒体"maxBufferSize="2147483647" maxReceivedMessageSize="2147483647"openTimeout="00:25:00" closeTimeout="00:25:00" sendTimeout="00:25:00" receiveTimeout="00:25:00"名称=网络绑定"><readerQuotas maxDepth="64"maxStringContentLength="2147483647"maxArrayLength="2147483647"maxBytesPerRead="2147483647"maxNameTableCharCount="2147483647"/></binding></webHttpBinding></绑定>

解决方案

wcf 的大数据传输问题:

我在 IIS 7、Windows 2008 服务器上托管了 wcf 4.0 服务.当我用小数据调用我的服务时说 4K 或 5K 字节然后请求很容易处理但是在尝试上传大尺寸时它给了我以下错误

  1. 错误请求 400
  2. 未找到文件 404 13,如 IIS 7 日志中所示
  3. 没有端点侦听服务myservice url"

在所有情况下,我都能够将小数据请求与我的客户端应用程序传输到服务器,但对于大消息.请求失败.

我已经尝试了所有可用的方法来解决这个问题,但对我没有任何效果.

在摸索了一个星期并阅读了所有文章和博客后,我终于想通了

<预><代码><配置><system.serviceModel><绑定><基本HttpBinding><binding name="myBinding" closeTimeout="00:10:00" maxBufferPoolSize="250000000" maxReceivedMessageSize="250000000" openTimeout="00:10:00" receiveTimeout="00:10:00" sendTimeout="00:10:00" messageEncoding="Text"><readerQuotas maxDepth="4500000" maxStringContentLength="4500000" maxBytesPerRead="40960000" maxNameTableCharCount="250000000" maxArrayLength="4500000"/></basicHttpBinding></绑定></system.serviceModel></配置><system.web><httpRuntime executionTimeout="4800" maxRequestLength="500000000"/></system.web><system.webServer><安全><请求过滤><requestLimits maxAllowedContentLength="500000000"></requestLimits></requestFiltering></安全></system.webServer><!-- 其他有用的设置--><serviceHostingEnvironment multipleSiteBindingsEnabled="true"/>

所以我认为这可能会对某些人有所帮助...

I am trying to upload large files to a WCF Service hosted in IIS.

I am using Restful and Streaming method.

But I am not able to upload files which is more than 64KB.

I tried lot by changing all the size-related elements in web.config file, but failed to fix the issue.

Here is my code and config, please let me know if anyone find any issues in the code and how can I fix.

Operation Contract

[OperationContract]
[WebInvoke(UriTemplate = "/UploadImage/{filename}")]
bool UploadImage(string filename, Stream image);

Implementation of Operation Contract

public bool UploadImage(string filename, Stream image)
{
    try
    {
        string strFileName = ConfigurationManager.AppSettings["UploadDrectory"].ToString() + filename;

        FileStream fileStream = null;
        using (fileStream = new FileStream(strFileName, FileMode.Create, FileAccess.Write, FileShare.None))
        {
            const int bufferLen = 1024;
            byte[] buffer = new byte[bufferLen];
            int count = 0;
            while ((count = image.Read(buffer, 0, bufferLen)) > 0)
            {
                fileStream.Write(buffer, 0, count);
            }
            fileStream.Close();
            image.Close();
        }

        return true;
    }
    catch (Exception ex)
    {
        return false;
    }
}

web.config

  <system.serviceModel>
    <services>
      <service name="Service" behaviorConfiguration="ServiceBehavior">
        <endpoint address="http://localhost/WCFService1" behaviorConfiguration="web"
                  binding="webHttpBinding" bindingConfiguration="webBinding"
                  contract="IService">
          <identity>
            <dns value="localhost"/>
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
      </service>
    </services>
    <bindings>
      <webHttpBinding>
        <binding name="webBinding"
            transferMode="Streamed"
            maxBufferSize="2147483647" maxReceivedMessageSize="2147483647"
            openTimeout="00:25:00" closeTimeout="00:25:00" sendTimeout="00:25:00" 
            receiveTimeout="00:25:00" >
        </binding>
      </webHttpBinding>
    </bindings>
    <behaviors>
      <serviceBehaviors>
        <behavior name="ServiceBehavior">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>

and

<httpRuntime maxRequestLength="2097151"/>

Service is hosted in hosted in IIS

Client side Code (console application)

private static void UploadImage()
{
    string filePath = @"F:\Sharath\TestImage\TextFiles\SampleText2.txt";
    string filename = Path.GetFileName(filePath);

    string url = "http://localhost/WCFService1/Service.svc/";
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url + "UploadImage/" + filename);

    request.Accept = "text/xml";
    request.Method = "POST";
    request.ContentType = "txt/plain";

    FileStream fst = File.Open(filePath, FileMode.Open);
    long imgLn = fst.Length;
    fst.Close();
    request.ContentLength = imgLn;

    using (Stream fileStream = File.OpenRead(filePath))
    using (Stream requestStream = request.GetRequestStream())
    {
            int bufferSize = 1024;
            byte[] buffer = new byte[bufferSize];
            int byteCount = 0;
            while ((byteCount = fileStream.Read(buffer, 0, bufferSize)) > 0)
            {
                requestStream.Write(buffer, 0, byteCount);
            }
    }

    string result;

    using (WebResponse response = request.GetResponse())
    using (StreamReader reader = new StreamReader(response.GetResponseStream()))
    {
            result = reader.ReadToEnd();
    }

    Console.WriteLine(result);
}

With this much of code I am able to upload 64KB of file, but when I try to upload a file of more than 64KB in size, I am getting error like,

The remote server returned an error: (400) Bad Request


i did what you told but still I am getting same problem, this is how my config looks like now, can you please tell me what is still missing here

<services>
  <service name="Service" behaviorConfiguration="ServiceBehavior">
    <endpoint address="http://localhost/WCFService1" behaviorConfiguration="web"
              binding="webHttpBinding" bindingConfiguration="webBinding"
              contract="IService">
      <identity>
        <dns value="localhost"/>
      </identity>
    </endpoint>
    <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
  </service>
</services>
<bindings>
  <webHttpBinding>
    <binding transferMode="Streamed"
             maxBufferSize="2147483647" maxReceivedMessageSize="2147483647"
             openTimeout="00:25:00" closeTimeout="00:25:00" sendTimeout="00:25:00" receiveTimeout="00:25:00"
             name="webBinding">
      <readerQuotas maxDepth="64" 
                    maxStringContentLength="2147483647" 
                    maxArrayLength="2147483647" 
                    maxBytesPerRead="2147483647" 
                    maxNameTableCharCount="2147483647"/>
    </binding>
  </webHttpBinding>
</bindings>

解决方案

The large data transfer issue with wcf:

I have wcf 4.0 service hosted on IIS 7, windows 2008 server. When I call my service with small data say 4K or 5K bytes then request get processed easily but while trying to upload large size it gave me following errors

  1. Bad Request 400
  2. File not found 404 13 as seen in IIS 7 logs
  3. There is no end point listening to the service "myservice url"

In all caseses I was able to transfer small data request with my client application to server but for large size message. Request failed.

I have tried all methods available to solve this issues but nothing worked for me.

After a scratching my head for a week and reading all articles and blogs finally I figured following

<configuration>
<system.serviceModel>
<bindings>
<basicHttpBinding>
        <binding name="myBinding" closeTimeout="00:10:00" maxBufferPoolSize="250000000" maxReceivedMessageSize="250000000" openTimeout="00:10:00" receiveTimeout="00:10:00" sendTimeout="00:10:00" messageEncoding="Text">
        <readerQuotas maxDepth="4500000" maxStringContentLength="4500000" maxBytesPerRead="40960000" maxNameTableCharCount="250000000" maxArrayLength="4500000"/>
            </basicHttpBinding>
        </bindings>
    </system.serviceModel>
</configuration>



<system.web>

    <httpRuntime executionTimeout="4800" maxRequestLength="500000000"/>
</system.web>

<system.webServer>
        <security>
            <requestFiltering>
                <requestLimits maxAllowedContentLength="500000000"></requestLimits>
            </requestFiltering>
        </security>
</system.webServer>

<!-- other useful setting -->

<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />

So I think It may help someone days....

这篇关于上传大文件的 WCF 问题,托管在 IIS 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆