none
WCF 上传文件服务发布到IIS报400 bad request错误 RRS feed

  • 问题

  • 有上传文件功能的WCF服务库,寄宿在控制台时,客户端能正常访问;寄宿到VS内置服务器后,就报400错误。是不是还需要对IIS设置什么才能正确运行呢?具体如何设置,谢谢。已经被这个问题折磨好几天了,完全不知道从哪儿开始分析看起。对比两种寄宿方式的配置文件,也没有发现什么特别有区别的地方。。

    IService1.cs:

        [ServiceContract]
        public interface IService1
        {
            [OperationContract]
            bool UploadFile(Stream inputStream);
        }

    Service1.cs:

        public class Service1 : IService1
        {
            public bool UploadFile(Stream inputStream)
            {
                var isSuccess = false;
    
                FileStream outputStream = null;
    
                try
                {
                    outputStream = new FileStream(@"d:\rec.dat",
                        FileMode.Create,
                        FileAccess.Write,
                        FileShare.None);
                    var buffer = new byte[4096];
                    var count = 0;
                    while ((count = inputStream.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        outputStream.Write(buffer, 0, count);
                    }
                    outputStream.Flush();
    
                    isSuccess = true;
                }
                catch (Exception e)
                {
                    isSuccess = false;
                }
                finally
                {
                    if (outputStream != null)
                    {
                        outputStream.Close();
                        outputStream.Dispose();
                    }
                    if (inputStream != null)
                    {
                        inputStream.Close();
                        inputStream.Dispose();
                    }
                }
    
                return isSuccess;
            }
        }

    控制台服务端配置:

    <?xml version="1.0"?>
    <configuration>
      <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
      </startup>
      <system.serviceModel>
        <services>
          <service name="Service.Service1" behaviorConfiguration="MessageBehavior">
            <endpoint
              binding="basicHttpBinding"
              contract="Service.IService1"
              bindingConfiguration="BasicHttpBinding_Service1" />
            <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
            <host>
              <baseAddresses>
                <add baseAddress="http://localhost:12345/Message/Streamed"/>
              </baseAddresses>
            </host>
          </service>
        </services>
        <behaviors>
          <serviceBehaviors>
            <behavior name="MessageBehavior">
              <serviceMetadata httpGetEnabled="true" />
              <serviceDebug includeExceptionDetailInFaults="true"/>
            </behavior>
          </serviceBehaviors>
        </behaviors>
        <bindings>
          <basicHttpBinding>
            <binding name="BasicHttpBinding_Service1" transferMode="Streamed" messageEncoding="Mtom" maxReceivedMessageSize="9223372036854775807" sendTimeout="00:10:00" receiveTimeout="00:10:00" />
          </basicHttpBinding>
        </bindings>
      </system.serviceModel>
    </configuration>

    IIS服务端配置:

    <?xml version="1.0"?>
    <configuration>
      <system.web>
        <compilation debug="true" targetFramework="4.0" />
      </system.web>
      <system.webServer>
         <modules runAllManagedModulesForAllRequests="true"/>
      </system.webServer>
      <system.serviceModel>
        <bindings>
          <basicHttpBinding>
            <binding name="BasicHttpBinding_Service1" transferMode="Streamed" maxReceivedMessageSize="9223372036854775807" sendTimeout="00:10:00" receiveTimeout="00:10:00" />
          </basicHttpBinding>
        </bindings>
        <services>
          <service name="Service.Service1" behaviorConfiguration="MessageBehavior">
            <endpoint binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_Service1" contract="Service.IService1" />
          </service>
        </services>
        <behaviors>
          <serviceBehaviors>
            <behavior name="MessageBehavior">
              <serviceMetadata httpGetEnabled="true"/>
              <serviceDebug includeExceptionDetailInFaults="true"/>
            </behavior>
          </serviceBehaviors>
        </behaviors>
        <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
      </system.serviceModel>  
    </configuration>

    客户端配置:

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
        <system.serviceModel>
            <bindings>
                <basicHttpBinding>
                    <binding name="BasicHttpBinding_IService1_IIS" closeTimeout="00:01:00"
                        openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
                        allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
                        maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="9223372036854775807"
                        messageEncoding="Text" textEncoding="utf-8" transferMode="Streamed"
                        useDefaultWebProxy="true">
                        <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
                            maxBytesPerRead="4096" maxNameTableCharCount="16384" />
                        <security mode="None">
                            <transport clientCredentialType="None" proxyCredentialType="None"
                                realm="" />
                            <message clientCredentialType="UserName" algorithmSuite="Default" />
                        </security>
                    </binding>
                    <binding name="BasicHttpBinding_IService1_CA" closeTimeout="00:01:00"
                        openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
                        allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
                        maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="9223372036854775807"
                        messageEncoding="Mtom" textEncoding="utf-8" transferMode="Streamed"
                        useDefaultWebProxy="true">
                        <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
                            maxBytesPerRead="4096" maxNameTableCharCount="16384" />
                        <security mode="None">
                            <transport clientCredentialType="None" proxyCredentialType="None"
                                realm="" />
                            <message clientCredentialType="UserName" algorithmSuite="Default" />
                        </security>
                    </binding>
                </basicHttpBinding>
            </bindings>
            <client>
                <endpoint address="http://localhost:2398/Service1.svc" binding="basicHttpBinding"
                    bindingConfiguration="BasicHttpBinding_IService1_IIS" contract="S1_IIS.IService1"
                    name="BasicHttpBinding_IService1" />
                <endpoint address="http://localhost:12345/Message/Streamed" binding="basicHttpBinding"
                    bindingConfiguration="BasicHttpBinding_IService1_CA" contract="S1_CA.IService1"
                    name="BasicHttpBinding_IService11" />
            </client>
        </system.serviceModel>
    </configuration>

    错误信息

    在 System.ServiceModel.ProtocolException 中第一次偶然出现的“mscorlib.dll”类型的异常
    System.ServiceModel.ProtocolException: 远程服务器返回了意外响应: (400) Bad Request。 ---> System.Net.WebException: 远程服务器返回错误: (400) 错误的请求。
       在 System.Net.HttpWebRequest.GetResponse()
       在 System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
       --- 内部异常堆栈跟踪的结尾 ---
    
    Server stack trace: 
       在 System.ServiceModel.Channels.HttpChannelUtilities.ValidateRequestReplyResponse(HttpWebRequest request, HttpWebResponse response, HttpChannelFactory factory, WebException responseException, ChannelBinding channelBinding)
       在 System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
       在 System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)
       在 System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout)
       在 System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
       在 System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
       在 System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
    
    Exception rethrown at [0]: 
       在 System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
       在 System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
       在 Client.S1_IIS.IService1.UploadFile(Stream inputStream)
       在 Client.MainWindow.worker_DoWork(Object sender, DoWorkEventArgs e) 位置 F:\Workspace\Demo\MyFileUpdate\Client\MainWindow.xaml.cs:行号 64

    下载源码




    QQ: 79965521 Email: WolfLai@126.com

    2015年5月3日 8:47

全部回复

  • Hi,

    我尝试了下你的代码,通过IIS的方式host你的wcf服务,能够成功的上传文件,需要注意的是你的Do_work方法,最好使用using以避免“The process cannot access the file because it is being used by another process ”错误,具体如下:

      void worker_DoWork(object sender, DoWorkEventArgs e)
            {
               using( var stream = new FileStream(fileName, FileMode.Open))
               { 

    如果你还是获得上述错误,我建议你去Wcf论坛提问.

    Best Regards,

    Jambor


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    2015年5月4日 6:03
    版主