Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > Распределённые приложения и сеть > проблема с импортом сервиса


Автор: nmn 1.11.2010, 21:20
здравтсвуйте

создал простой сервер веб сервиса на php

Код

<?php
// load SOAP library
require_once("lib/nusoap.php");
require_once("lib/functions.php");
// load library that holds implementations of functions we're making available to the web service
// set namespace
$ns="";//"http://localhost/wsdl/";
// create SOAP server object
$server = new soap_server();
// setup WSDL file, a WSDL file can contain multiple services
$server->configureWSDL('Calculator',$ns);
$server->wsdl->schemaTargetNamespace=$ns;
// register a web service method
$server->register('ws_add',
    array('int1' => 'xsd:int','int2' => 'xsd:int'),    // input parameters
    array('total' => 'xsd:int'),                            // output parameter
    $ns,                                                        // namespace
    "$ns#ws_add",                                             // soapaction
    'rpc',                                                   // style
    'encoded',                                               // use
    'adds two integer values and returns the result'            // documentation
    );

function ws_add($int1, $int2){
    return $int1 + $int2;
//return new soapval('return','xsd:integer', $int1 + $int2);
}
// service the methods 
$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
$server->service($HTTP_RAW_POST_DATA);
?>


если его импортировать при помощи студии, то при попытке вызова метода выбрасывается исключение
Код

mywsdl.CalculatorPortTypeClient b = new mywsdl.CalculatorPortTypeClient();
res = b.ws_add(1, 1);//exception!!!


Код

Тип содержимого text/xml; charset=ISO-8859-1 ответного сообщения не соответствует типу содержимого привязки (text/xml; charset=utf-8).
При использовании особого кодировщика необходимо правильно реализовать метод IsContentTypeSupported. Первые 527 байтов ответного
сообщения: "<?xml version="1.0" encoding="ISO-8859-1"?><SOAP-ENV:Envelope SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org
/soap/encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"><SOAP-ENV:Body>
<ns1:ws_addResponse xmlns:ns1="http://schemas.xmlsoap.org/soap/envelope/"><total xsi:type="xsd:int">2</total></ns1:ws_addResponse>
</SOAP-ENV:Body></SOAP-ENV:Envelope>".


однако если импортировать при помощи утилиты wsdl.exe, то никаких исключений не выбрасывается и метод отрабатывает как надо

Автор: jonie 1.11.2010, 23:03
я бы в веш сервис добавил такие хедеры:
Код


header("Expires: Mon, 26 Jul 1997 05:00:00 GMT" );
header("Last-Modified: " . gmdate( "D, d M Y H:i:s" ) . "GMT" );
header("Cache-Control: no-cache, must-revalidate" );
header("Pragma: no-cache" );
//header("Content-type: application/soap+xml; charset=utf-8");  //мб нуСОАП научился сам ставить нечто вроде того
...
$server->service(utf8_encode($HTTP_RAW_POST_DATA)); //utf-8 отдаём


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

Автор: nmn 2.11.2010, 10:21
поменял в объявлении class $wsdl->soap_def_encoding на UTF-8 (он там был закомментирован) и теперь импортируется нормально

Автор: SectoR 27.4.2011, 12:02
Я взял ваш php-пример для тестирования:
Код

// load SOAP library
    require_once("/usr/local/php/lib/nusoap-0.9.5/lib/nusoap.php");
    
    function service_server() {
    
        $wsdl->soap_def_encoding = "UTF-8";
        
        // set namespace
        $ns="";//"http://hqmskcontrol/wsdl/";
        
        // create SOAP server object
        $server = new soap_server();
        $wsdl->soap_defencoding = "UTF-8";
        
        // setup WSDL file, a WSDL file can contain multiple services
        $server->configureWSDL('Calculator',$ns);
        $server->wsdl->schemaTargetNamespace=$ns;
        
        // register a web service method
        $server->register('ws_add',
            array('int1' => 'xsd:int','int2' => 'xsd:int'),    // input parameters
            array('total' => 'xsd:int'),                       // output parameter
            $ns,                                               // namespace
            "$ns#ws_add",                                      // soapaction
            'rpc',                                             // style
            'encoded',                                         // use
            'adds two integer values and returns the result'   // documentation
        );
        
        function ws_add($int1, $int2){
            return $int1 + $int2;
            //return new soapval('return','xsd:integer', $int1 + $int2);
        }
        
        // service the methods 
        $HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
        $server->service( utf8_encode($HTTP_RAW_POST_DATA) );
    }

web-сервис прекрасно работает...

Создаю ссылку на службу - тоже все прекрасно, но вот след. код:
Код

phpcalc.CalculatorPortTypeClient client = new phpcalc.CalculatorPortTypeClient();
            
            int res = 0;
            try
            {
                res = client.ws_add(2, 2);
            }
            // вызывается при ошибке связи в службе или клиентском приложении
            catch (System.ServiceModel.CommunicationException e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine(e.InnerException);
                //Console.WriteLine(e.StackTrace);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            Console.WriteLine(res);

выдает исключение:


Код

Сервер вернул недопустимое сообщение об ошибке SOAP. Дополнительные сведения см.
 в описании внутреннего исключения.

System.Xml.XmlException: Элемент "faultstring" с пространством имен "" не найден
. Строка 6, позиция 126.
   в System.Xml.XmlReader.CheckElement(String localName, String namespaceURI)
   в System.Xml.XmlReader.ReadElementContentAsString(String localName, String na
mespaceURI)
   в System.ServiceModel.Channels.ReceivedFault.CreateFault11(XmlDictionaryReade
r reader, Int32 maxBufferSize)
   в System.ServiceModel.Channels.MessageFault.CreateFault(Message message, Int3
2 maxBufferSize)
0


подскажите, как исправить?

Автор: SectoR 12.5.2011, 13:46
Проблема решена...
оказалось нужно вместо Service Reference использовать Web Reference в C#
http://forum.sources.ru/index.php?showtopic=330908

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)