Вызов WCF из веб-исключения - PullRequest
1 голос
/ 09 июля 2020

Я новичок в создании веб-служб, и у меня возникли некоторые ошибки после создания веб-службы с использованием WCF и развертывания ее в IIS, когда я пытался протестировать ее с помощью веб-браузера, он возвращает мне эту ошибку, которую я не получаю:

An ExceptionDetail, likely created by IncludeExceptionDetailInFaults=true, whose value is:
System.NullReferenceException: Object reference not set to an instance of an object.
   at System.ServiceModel.Description.WsdlExporter.CreateWsdlBindingAndPort(ServiceEndpoint endpoint, XmlQualifiedName wsdlServiceQName, Port& wsdlPort, Boolean& newBinding, Boolean& bindingNameWasUniquified)
   at System.ServiceModel.Description.WsdlExporter.ExportEndpoint(ServiceEndpoint endpoint, XmlQualifiedName wsdlServiceQName, BindingParameterCollection bindingParameters)
   at System.ServiceModel.Description.WsdlExporter.ExportEndpoints(IEnumerable`1 endpoints, XmlQualifiedName wsdlServiceQName, BindingParameterCollection bindingParameters)
   at System.ServiceModel.Description.ServiceMetadataBehavior.MetadataExtensionInitializer.GenerateMetadata()
   at System.ServiceModel.Description.ServiceMetadataExtension.EnsureInitialized()
   at System.ServiceModel.Description.ServiceMetadataExtension.HttpGetImpl.InitializationData.InitializeFrom(ServiceMetadataExtension extension)
   at System.ServiceModel.Description.ServiceMetadataExtension.HttpGetImpl.GetInitData()
   at System.ServiceModel.Description.ServiceMetadataExtension.HttpGetImpl.TryHandleDocumentationRequest(Message httpGetRequest, String[] queries, Message& replyMessage)
   at System.ServiceModel.Description.ServiceMetadataExtension.HttpGetImpl.ProcessHttpRequest(Message httpGetRequest)
   at SyncInvokeGet(Object , Object[] , Object[] )
   at System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]& outputs)
   at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc)
   at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc)
   at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage11(MessageRpc& rpc)
   at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)

веб-конфигурация:

<?xml version="1.0"?>
<configuration>

  <connectionStrings>

    <add name="ConnectionString" connectionString=... />

  </connectionStrings>

  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="false" />
    <add key="wcf:serviceHostingEnvironment:useClassicReadEntityBodyMode" value="true" />
  </appSettings>


  <system.web>
    <httpRuntime maxRequestLength="4000480" executionTimeout="600" />
    <compilation debug="true" targetFramework="4.0" />
    <customErrors mode="Off" />
    <authentication mode="Windows" />
    <pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID" />
    <sessionState mode="Off" />
  </system.web>




  <system.webServer>



    <directoryBrowse enabled="true" />

  
   
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="Content-Type, Accept" />
        <add name="Access-Control-Allow-Methods" value="POST,GET,OPTIONS" />
        <add name="Access-Control-Max-Age" value="1728000" />
      </customHeaders>
    </httpProtocol>

  </system.webServer>


  <system.serviceModel>
    <services>      

      <service name="CLService.Service1" behaviorConfiguration="Service1Behavior">
        <endpoint address="unsecure/XML" binding="webHttpBinding" bindingConfiguration="webHttpBinding" contract="CLService.IService1" behaviorConfiguration="RestXMLEndpointBehavior" />
        <endpoint address="unsecure" binding="webHttpBinding" bindingConfiguration="webHttpBinding" contract="CLService.IService1" behaviorConfiguration="RestJSONEndpointBehavior" />

        <endpoint address="xml2" binding="webHttpBinding" bindingConfiguration="webHttpsBinding" contract="CLService.IService1" behaviorConfiguration="RestXMLEndpointBehavior" />
        <endpoint address="json" binding="webHttpBinding" bindingConfiguration="webHttpsBinding" contract="CLService.IService1" behaviorConfiguration="RestJSONEndpointBehavior" />
      </service>
    </services>
      
  

    <behaviors>
      <endpointBehaviors>

        <behavior name="RestJSONEndpointBehavior">
          <webHttp helpEnabled="false" defaultOutgoingResponseFormat="Json" />
          <!--  <webHttp automaticFormatSelectionEnabled="true" -->

        </behavior>
        <behavior name="RestXMLEndpointBehavior">
          <webHttp helpEnabled="false" defaultOutgoingResponseFormat="Xml" />
        </behavior>
      </endpointBehaviors>

      <serviceBehaviors>
        <behavior name="Service1Behavior">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug httpHelpPageEnabled="false" includeExceptionDetailInFaults="true" />
          <serviceThrottling maxConcurrentCalls="200" maxConcurrentSessions="500" maxConcurrentInstances="600" />
        </behavior>
        <behavior name="">
          <serviceThrottling maxConcurrentCalls="200" maxConcurrentSessions="500" maxConcurrentInstances="600" />
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>


    <bindings>

      <webHttpBinding>
        
        <binding name="webHttpsBinding" crossDomainScriptAccessEnabled="true" maxBufferSize="2000000000" maxReceivedMessageSize="2000000000" transferMode="Buffered" closeTimeout="00:10:00" openTimeout="00:10:00" receiveTimeout="00:10:00" sendTimeout="00:10:00">
          <readerQuotas maxDepth="250000000" maxStringContentLength="250000000" maxArrayLength="250000000" maxBytesPerRead="250000000" maxNameTableCharCount="250000000" />
          <security mode="Transport">
            <transport clientCredentialType="None" />
          </security>
        </binding>

        <binding name="webHttpBinding" maxBufferPoolSize="9990000" maxBufferSize="2000000000" maxReceivedMessageSize="2000000000" closeTimeout="00:10:00" openTimeout="00:10:00" receiveTimeout="00:10:00" sendTimeout="00:10:00" transferMode="Buffered">
          <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />

          <security mode="None" />
        </binding>
      </webHttpBinding>

      <basicHttpBinding>
        <binding name="Service1Soap" />

        <binding name="secureHttpBinding">
          <security mode="Transport">
            <transport clientCredentialType="None" />
          </security>
        </binding>
      </basicHttpBinding>

    </bindings>


    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" minFreeMemoryPercentageToActivateService="0" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>

</configuration>

мои методы контракта на обслуживание внутри IService1:

    [OperationContract]
    [WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, UriTemplate = "Mthod1", BodyStyle = WebMessageBodyStyle.Wrapped)]
    Response Mthod1(String Query);



    [OperationContract]
    [WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, UriTemplate = "Mthod2",BodyStyle = WebMessageBodyStyle.Wrapped)]
    Response Mthod2(String Query);

Я безуспешно пытался изменить поведение и привязки

веб-служба развернута на IIS с использованием https.

есть идеи, в чем может быть проблема? Заранее благодарю

1 Ответ

0 голосов
/ 10 июля 2020

Поскольку контракт CLService.IService1 предоставляется на нескольких конечных точках, клиентское приложение должно ссылаться на имя конечной точки при создании экземпляра прокси для контракта. Если имя конечной точки не подтверждено, WCF выдаст ошибку, потому что не может знать, какую конечную точку использовать.

Если вы используете браузер для открытия файла .sv c напрямую, сервер сообщит об ошибке потому что он не знает, какую конечную точку вы хотите использовать. Вам необходимо добавить адрес конечной точки, к которой вы хотите получить доступ, после файла .sv c.

После моего тестирования эта ошибка не повлияет на нормальный доступ программы. Это просто ошибка, из-за которой сервер не знает, какую конечную точку вы будете использовать. Вам необходимо сообщить службе, к какой конечной точке вам нужен доступ.

...