Форум программистов
 

Восстановите пароль или Зарегистрируйтесь на форуме, о проблемах и с заказом рекламы пишите сюда - alarforum@yandex.ru, проверяйте папку спам!

Вернуться   Форум программистов > .NET Frameworks (точка нет фреймворки) > C# (си шарп)
Регистрация

Восстановить пароль
Повторная активизация e-mail

Купить рекламу на форуме - 42 тыс руб за месяц

Ответ
 
Опции темы Поиск в этой теме
Старый 03.12.2013, 17:59   #1
EniOk
Пользователь
 
Аватар для EniOk
 
Регистрация: 07.06.2009
Сообщений: 43
По умолчанию WCF служба и JSON

Возникла задача подружить такую службу и JSON.

Службу написал - через SOUPUI работает но в XML формате... Хотя у интерфейса прописан метод:
Код:
        [OperationContract]
        [WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json,
            BodyStyle = WebMessageBodyStyle.Wrapped,
             UriTemplate = "/GetData/"
            )]
         string GetData(string email, Int64 phone, NAME name, string dob, int secret, Int64 card);
В web.config:
Код:
<?xml version="1.0" encoding="utf-8"?>
<configuration>

  <system.web>
    <compilation debug="true" targetFramework="4.0" />
    <customErrors mode="Off"/>

  </system.web>
  <system.serviceModel>
    <services>
      <service name="DWH.IService1" behaviorConfiguration="goodbeh">
        <endpoint address="" binding="webHttpBinding" contract="DWH.IService1" behaviorConfiguration="web"></endpoint>
      </service>
    
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="goodbeh">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
        <behavior>
          <serviceMetadata httpGetEnabled="true"/>
                 <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="web">
          <webHttp/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
 <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <directoryBrowse enabled="true"/>
  </system.webServer>

</configuration>
Всю голову сломал уже...
При попытке послать JSON запрос:
Код:
POST http://127.0.0.1/Service1.svc/GetData/ HTTP/1.1
Content-Type: application/json
Host: localhost
Content-Length: 231
Expect: 100-continue
Proxy-Connection: Keep-Alive

{"card":1111222255558888,"dob":"2013-02-02","email":"email@server.domain","name":{"Name":"Р?ван","Patronymic":"Р?ванович","Surname":"Р?ванов"},"phone":79991234567,"secret":159357}
получаю ответ о ошибке 415 -
Код:
HTTP/1.1 415 Cannot process the message because the content type 'application/json' was not the expected type 'text/xml; charset=utf-8'.
Via: 1.1 PROXY
Connection: Keep-Alive
Proxy-Connection: Keep-Alive
Content-Length: 0
Date: Tue, 03 Dec 2013 13:56:58 GMT
Server: Microsoft-IIS/7.5
X-Powered-By: ASP.NET
Что делать? =(
EniOk вне форума Ответить с цитированием
Старый 03.12.2013, 18:50   #2
EniOk
Пользователь
 
Аватар для EniOk
 
Регистрация: 07.06.2009
Сообщений: 43
По умолчанию

Видоизменил конфиг:
Код:
<?xml version="1.0" encoding="utf-8"?>
<configuration>

  <system.web>
    <compilation debug="true" targetFramework="4.0" />
    <customErrors mode="Off"/>

  </system.web>
  <system.serviceModel>
    <services>
      <service name="DWH.IService1" behaviorConfiguration="goodbeh">
        <endpoint address="" binding="webHttpBinding" contract="DWH.IService1" behaviorConfiguration="web"></endpoint>
      <endpoint address="json" binding="webHttpBinding" behaviorConfiguration="jsonBehavior" contract="DWH.IService1" />
      </service>
    
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="goodbeh">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>

        <behavior>
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="web">
          <webHttp/>
        </behavior>
        <behavior name="jsonBehavior">
          <enableWebScript/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
 <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <directoryBrowse enabled="true"/>
  </system.webServer>

</configuration>
И посылаю запрос к http://127.0.0.1/Service1.svc/json/GetData.
Проблема осталась =(
EniOk вне форума Ответить с цитированием
Старый 04.12.2013, 15:17   #3
EniOk
Пользователь
 
Аватар для EniOk
 
Регистрация: 07.06.2009
Сообщений: 43
По умолчанию

Еще раз переписал конфиг, добавил поддержку ASPNET, дописал WebInwoke в реализацию класса и вроде, тьфу-тьфу, заработало...

Код:
<?xml version="1.0"?>
<configuration>
  <!--
    Описание изменений web.config см. по адресу http://go.microsoft.com/fwlink/?LinkId=235367.

    Следующие атрибуты можно установить с помощью тега <httpRuntime>.
      <system.Web>
        <httpRuntime targetFramework="4.5.1" />
      </system.Web>
  -->
  <system.web>
    <compilation debug="true" targetFramework="4.5"/>
    <customErrors mode="Off"/>
    <pages controlRenderingCompatibilityVersion="4.0"/>
  </system.web>
  <system.serviceModel>
    <!--serviceHostingEnvironment aspNetCompatibilityEnabled="true" /-->
    <diagnostics>
      <messageLogging logMalformedMessages="true" logMessagesAtTransportLevel="true"/>
    </diagnostics>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" >
      <serviceActivations>
        <add factory="System.ServiceModel.Activation.WebServiceHostFactory"
             relativeAddress="./Service1.svc" service ="DWH.Service1"/>
      </serviceActivations>
    </serviceHostingEnvironment>
      <services>
      <service behaviorConfiguration="serviceBehavior" name="DWH.Service1">
        <endpoint address="" behaviorConfiguration="jsonEndpointBehavior" binding="webHttpBinding" name="json" contract="DWH.IService1"/>
        <endpoint address="json" behaviorConfiguration="jsonEndpointBehavior" binding="webHttpBinding" name="json" contract="DWH.IService1">
          <!--identity>
            <dns value="localhost" />
          </identity-->
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" name="mex" contract="IMetadataExchange"/>
        <endpoint address="wsHttpBinding" behaviorConfiguration="wsHttpBinding" binding="wsHttpBinding" bindingConfiguration="" name="wsHttpBinding" contract="DWH.IService1">
          <identity>
            <dns value="localhost/wsHttpBinding"/>
          </identity>
        </endpoint>
      </service>
    </services>
    <behaviors>
      <endpointBehaviors>
        <behavior name="jsonEndpointBehavior">
          <webHttp helpEnabled="True" defaultOutgoingResponseFormat ="Json" automaticFormatSelectionEnabled="False"/>
          
        </behavior>
        <behavior name="wsHttpBinding">
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="true"/>
          
        </behavior>
        <behavior name="serviceBehavior">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
  <!--system.serviceModel>
    <services>
      <service name="DWH.IService1" behaviorConfiguration="goodbeh">
        <endpoint address="" binding="webHttpBinding" contract="DWH.IService1" behaviorConfiguration="web"></endpoint>
        <endpoint address="json" binding="webHttpBinding" behaviorConfiguration="jsonBehavior" contract="DWH.IService1"  />
        <endpoint address="mex" binding="webHttpBinding" behaviorConfiguration="jsonBehavior" contract="DWH.IService1"  />
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="goodbeh">
          <serviceMetadata httpGetEnabled="true"/>
                 <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
        <behavior>
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="web">
          <webHttp/>
        </behavior>
        <behavior name="jsonBehavior"  >
          <dataContractSerializer/>
          <enableWebScript/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel-->
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <directoryBrowse enabled="true"/>
  </system.webServer>
</configuration>
Остальное вроде итак ясно =)

Спасибо, если кто-то думал над проблемой...

Может кому-то будет полезен данный код
EniOk вне форума Ответить с цитированием
Ответ


Купить рекламу на форуме - 42 тыс руб за месяц



Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
WCF Inv1s Общие вопросы .NET 1 16.02.2013 20:54
WCF HenryL C# (си шарп) 1 24.02.2012 18:06
WCF авторизация kaljan775 Общие вопросы .NET 0 04.10.2011 12:26
WPF, WCF!! Thugmaster WPF, UWP, WinRT, XAML 1 22.09.2010 21:00
WCF + Ip Malder Общие вопросы .NET 0 29.08.2008 22:58