Wcf Restful Api服务下载大文件-.Net

问题描述 投票:0回答:1

我已经使用 Wcf 服务在 restful api 上创建了。我正在使用此服务通过流下载文件。在本地主机上它工作正常,但是当我使用 url 从远程浏览器使用它时,它在下载一些数据后停止了。前任。总文件大小为 600mb,在本地主机上我可以下载所有文件,但是当我从远程浏览器使用它时它开始下载(10、20、50、126Mb)并在两者之间停止并在一段时间后出现网络错误。

在我的代码下面,如果我遗漏了什么。

服务合同:

<ServiceContract>
Public Interface IService   
    <OperationContract()>
    <WebGet(UriTemplate:="File/{Param}", ResponseFormat:=WebMessageFormat.Json, BodyStyle:=WebMessageBodyStyle.Bare)>
    Function FileDownloadRequest(Param As String) As Stream
End Interface

请求处理程序:

<ServiceBehavior(InstanceContextMode:=InstanceContextMode.Single, ConcurrencyMode:=ConcurrencyMode.Multiple, UseSynchronizationContext:=False)>
Public Class RequestHandler
    Implements IService

Private Function FileDownloadRequest(Param As String) As Stream Implements IService.FileDownloadRequest
        Dim _FileName As String = RootFolder & "\" & Param
        Try
            ReqLogs.Add("<<-- Download request recieved for " & _FileName)
            '
            'Header Set For CORS
            '
            WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Origin", "*")
            If (WebOperationContext.Current.IncomingRequest.Method = "OPTIONS") Then
                WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Methods", "*")
                WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Headers", "*, Content-Type, Accept")
                WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Max-Age", "1728000")
            End If
            If File.Exists(_FileName) Then
                WebOperationContext.Current.OutgoingResponse.Headers("Content-Disposition") = "attachment; filename=" + "Report Data.csv"
                WebOperationContext.Current.OutgoingResponse.ContentType = "application/octet-stream"
                WebOperationContext.Current.OutgoingResponse.StatusCode = Net.HttpStatusCode.OK

                Dim _FStream As New FileStream(_FileName, FileMode.Open, FileAccess.Read)
                WebOperationContext.Current.OutgoingResponse.ContentLength = _FStream.Length
                ReqLogs.Add("<<-- Download processing..... ++ " & _FStream.Length.ToString)
                Return _FStream
            Else
                ReqLogs.Add("---- File not found to download !!!")
                Throw New Exception("File not found to download")
            End If
        Catch ex As Exception
            ReqLogs.Add("Download event error: " & ex.Message)
            WebOperationContext.Current.OutgoingResponse.StatusCode = Net.HttpStatusCode.InternalServerError
            Return Nothing
        End Try
    End Function

End Class

初始化服务:

Private _WcfServer As WebServiceHost

_WcfServer = New WebServiceHost(GetType(RequestHandler), New Uri("http://localhost:6700/"))
Dim _Binding As New WebHttpBinding With {
                    .Name = "IService",
                    .MaxBufferSize = 2147483647,
                    .MaxBufferPoolSize = 2147483647,
                    .MaxReceivedMessageSize = 2147483647,
                    .TransferMode = TransferMode.Streamed,
                    .ReceiveTimeout = New TimeSpan(0, 0, 1, 0, 0),
                    .SendTimeout = New TimeSpan(0, 0, 10, 0, 0)
                }
                _Binding.ReaderQuotas.MaxDepth = 2147483647
                _Binding.ReaderQuotas.MaxStringContentLength = 2147483647
                _Binding.ReaderQuotas.MaxBytesPerRead = 2147483647
                _Binding.ReaderQuotas.MaxArrayLength = 2147483647
                _Binding.ReaderQuotas.MaxNameTableCharCount = 2147483647
                _Binding.Security.Mode = WebHttpSecurityMode.None

                _WcfServer.AddServiceEndpoint(GetType(IService), _Binding, "")
                Dim _ServiceBehavior As New ServiceMetadataBehavior With {
                    .HttpGetEnabled = True
                }
                _WcfServer.Description.Behaviors.Add(_ServiceBehavior)

                _WcfServer.Open()

App.config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
    <system.serviceModel>
        <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
        <bindings>
          <basicHttpBinding>
            <binding name="Middleware.IService" transferMode="Streamed" receiveTimeout="00:10:00" sendTimeout="00:10:00" maxReceivedMessageSize="2147483647" >
              <readerQuotas  maxArrayLength="2147483647" maxStringContentLength="2147483647" />
              <security mode="TransportCredentialOnly">
                <transport clientCredentialType="Windows"></transport>
              </security>
            </binding>
          </basicHttpBinding>
          <wsHttpBinding>
            <binding name="Middleware.IService" messageEncoding="Mtom"/>
          </wsHttpBinding>
        </bindings>
          <!--<behaviors>
            <endpointBehaviors>
              <behavior name="IService">
                <webHttp defaultOutgoingResponseFormat="Json" defaultBodyStyle="Wrapped" automaticFormatSelectionEnabled="false"/>
              </behavior>
            </endpointBehaviors>
            <serviceBehaviors>
              <behavior name="">
                <serviceMetadata httpGetEnabled="true" />
                <serviceDebug includeExceptionDetailInFaults="true" />
              </behavior>
            </serviceBehaviors>
          </behaviors>-->
        <services>
          <!--<service name="FileHandling.WCFHost.FileManagerService">
            <endpoint address=""
                  binding="webHttpBinding"
                  bindingConfiguration="ServiceWebBindingName"
                  behaviorConfiguration="DefaultRestServiceBehavior"
                  name="FileManagerServiceEndpoint"
                  contract="FileHandling.WCFHost.IFileManagerService"/>
          </service>-->
        </services>
    </system.serviceModel>
</configuration>

通过痕迹的异常:

semaphore timeout period has expired
asp.net .net vb.net wcf wcf-rest
1个回答
0
投票

你提到在本地运行没问题,但是在远程设备上有问题。

1.由于设备。我们从WCF服务器取数据的速度太慢,导致服务器一段时间没有响应,最后断开连接。基于此,我认为可以更换设备进行验证。

2.服务器端存储数据后,使用一个线程将数据移动到另一个内存缓存中,按理说只是占用了更多内存,应该不会影响接收请求的速度,其实,我想去掉很多内存除了多开几个线程,还伴随着大量内存到文件IO写出,导致线程打开延迟。

基于此,我觉得一个很好的方法说使用using()来及时清理线程。

3.你可以试试在System.Web上添加:

<httpRuntimemaxRequestLength="102400" />

4.Invoke the service script on initial load: ASP.NET Site Warmup

5.当你的服务上传到IIS后,你可以查看配置文件是否有变化。

最好的问候

© www.soinside.com 2019 - 2024. All rights reserved.