Wcf System.ServiceModel.ProtocolException:'远程服务器返回了意外的响应:(400)Bad Request。'

时间:2017-11-22 07:17:17

标签: c# web-services wcf iis nhibernate

我正在尝试测试我的WCF服务是包括方法创建,更新,getlist到Sql Server vs.。它在浏览器上运行GET方法但我想在Console app上测试POST方法。所以我的服务引用它到控制台app.I得到这个错误;

System.ServiceModel.ProtocolException:'远程服务器返回了意外响应:(400)错误请求。'

内部例外 WebException:远程服务器返回错误:(400)错误请求

修改!!

ERROR: System.ServiceModel.ProtocolException:远程服务器返回了意外响应:(405)Method Not Allowed。 ---> System.Net.WebException:远程服务器返回错误:(405)Method Not Allowed。    在System.Net.HttpWebRequest.GetResponse()    在System.ServiceModel.Channels.HttpChannelFactory 1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout) --- End of inner exception stack trace --- Server stack trace: at System.ServiceModel.Channels.HttpChannelUtilities.ValidateRequestReplyResponse(HttpWebRequest request, HttpWebResponse response, HttpChannelFactory 1工厂,WebException responseException,ChannelBinding channelBinding)    at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)    在System.ServiceModel.Channels.RequestChannel.Request(消息消息,TimeSpan超时)    在System.ServiceModel.Dispatcher.RequestChannelBinder.Request(消息消息,TimeSpan超时)    在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操作)    在System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage消息) 在[0]处重新抛出异常:    在System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg,IMessage retMsg)    在System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData,Int32 type)    在WSTester.WorkWS.IService1.GetCustomerList()    在C:\ Users \ aykut \ source \ repos \ Work \ WSTester \ Connected Services \ WorkWS \ Reference.cs中的WSTester.WorkWS.Service1Client.GetCustomerList():第291行    at WSTester.Program.Main(String [] args)在C:\ Users \ aykut \ source \ repos \ Work \ WSTester \ Program.cs:第47行

Thanx的建议。 这是我在Console APP中的App.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
  </startup>

  <system.serviceModel>

    <bindings>
      <webHttpBinding>
        <binding name="webHttpBindingWithJsonP"
                 maxReceivedMessageSize="1048576"/>
      </webHttpBinding>
   </bindings>
    <client>
      <endpoint address="http://192.168.0.XX:7767/Service1.svc"
        binding="webHttpBinding"
        contract="WorkWS.IService1" behaviorConfiguration="webhttp" />
    </client>
    <behaviors>
      <endpointBehaviors>
        <behavior name="webhttp">
          <webHttp/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
  </system.serviceModel>
</configuration>

这是我在WebService中的Web.config:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="hibernate-configuration" type="NHibernate.Cfg.ConfigurationSectionHandler,NHibernate" />
  </configSections>
  <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
    <session-factory>
      <property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
      <property name="dialect">NHibernate.Dialect.MsSql2012Dialect</property>
      <property name="connection.connection_string">Data Source=.\SQLEXPRESS;;Initial Catalog=FirstProject; User Id = aykut ; password= 1234</property>
      <property name="show_sql">true</property>
    </session-factory>
  </hibernate-configuration>
 <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
    <add key="HBM_ASSEMBLY" value="BusinessEntities" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.6.1" />
    <httpRuntime targetFramework="4.6.1" />
        <identity impersonate="false" />
        <authentication mode="Forms" />
      </system.web>
  <system.serviceModel>
    <services>
      <service name="WebService.Service1">
        <endpoint address="" behaviorConfiguration="webHttpBehavior" binding="webHttpBinding" bindingConfiguration="webHttpBindingWithJsonP" contract="WebService.IService1" />
      </service>
    </services>
    <bindings>
      <webHttpBinding>
        <binding name="webHttpBindingWithJsonP" crossDomainScriptAccessEnabled="true" />
      </webHttpBinding>
    </bindings>

    <behaviors>
      <endpointBehaviors>
        <behavior name="webHttpBehavior">
          <webHttp />
        </behavior>
      </endpointBehaviors>

      <serviceBehaviors>
        <behavior>
          <!-- Meta veri bilgilerini açığa çıkarmaktan kaçınmak için, dağıtımdan önce aşağıdaki bilgileri false yapın -->
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
          <!-- Hatalarda hata ayıklamak amacıyla özel durum ayrıntıları almak için aşağıdaki değeri true yapın.  Özel durum bilgilerini açığa çıkarmaktan kaçınmak için dağıtımdan önce false yapın -->
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>
 <modules runAllManagedModulesForAllRequests="true" />
    <!--
        To browse web app root directory during debugging, set the value below to true.
        Set to false before deployment to avoid disclosing web app folder information.
      -->
    <directoryBrowse enabled="true" />
  </system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Iesi.Collections" publicKeyToken="aa95f207798dfdb4" culture="neutral" />
      <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

这是我的主要方法;

   static void Main(string[] args)
    {
        Service1Client client = new Service1Client();
        Customer c = new Customer();
        c.Name = "dsfsfsdf";
        c.SurName="asdass";
        c.Age = 12;
        client.CreateCustomer(c);
    }

EDIT !! 这是我的Service1.svc:

    public class Service1 : IService1
    {
        [WebInvoke(Method = "GET",
        ResponseFormat = WebMessageFormat.Json,
        UriTemplate = "GetCustomerList")]
        public List<Customer> GetCustomerList()
        {
            CustomerFinder cm = new CustomerFinder();
            List<Customer> customerlist = cm.GetAllCustomers();
            return customerlist;
        }
        [WebInvoke(Method = "GET",
        ResponseFormat = WebMessageFormat.Json,
        BodyStyle = WebMessageBodyStyle.WrappedRequest,
        UriTemplate = "GetCustomerByID/{id}")]
        public Customer GetCustomerByID(string id)
        {
            CustomerFinder cm = new CustomerFinder();
            Customer customer = cm.FindByID(Int32.Parse(id));
            return customer;
        }

        [WebInvoke(Method = "POST",
        UriTemplate = "CreateCustomer",
        BodyStyle = WebMessageBodyStyle.WrappedRequest,
        RequestFormat = WebMessageFormat.Json,
        ResponseFormat = WebMessageFormat.Json)]
        public Customer CreateCustomer(Customer customer)
        {
            if (customer == null)
            {
                throw new ArgumentNullException("FAIL");
            }
            CustomerManager cm = new CustomerManager();
            cm.CreateCustomer(customer);
        return customer;
        }
}

这是IService:

    public interface IService1
    {

        [OperationContract]
        List<Customer> GetCustomerList();

        [OperationContract]
        Customer GetCustomerByID(string id);

        [OperationContract]
        Customer CreateCustomer(Customer customer);

        [OperationContract]
        void DeleteCustomerByID(string id);
    }

}

这是我的CreateCustomer方法:

public class CustomerManager : BusinessComponentBase
{
    public Customer CreateCustomer(Customer customer)
    {
        ISession session = this.GetSession();
        using (var tx = session.BeginTransaction())
        {
            try
            {
                this.GetSession().Save(customer);               
                this.GetSession().Save(customer.Addresses);
                tx.Commit();

            }
            catch
            {
                tx.Rollback();
            }
        }
        return customer;
    }

1 个答案:

答案 0 :(得分:0)

我找到了解决方案。 .Problem在CreateCustomer方法上。当我在sql服务器上实现我的表时,地址不能为空并且它们已经映射,因此不需要以这种方式保存(customer.Addresses);

    public Customer CreateCustomer(Customer customer)
    {
        ISession session = this.GetSession();
        using (var tx = session.BeginTransaction())
        {
            try
            {
                this.GetSession().Save(customer);
                tx.Commit();
            }
            catch(Exception e)
            {
                tx.Rollback();
            }
        }
        return customer;
    }