2016-07-08 4 views
4

У меня есть RESTful сервис, который имеет этот OperationContractОшибка 415 при тестировании моей службы WCF

[OperationContract] 
[WebInvoke(Method = "POST", 
    ResponseFormat = WebMessageFormat.Json, 
    BodyStyle = WebMessageBodyStyle.Wrapped, 
    UriTemplate = "json")] 
Response JSONData(Request request); 

и сконфигурирован таким образом

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

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

    <system.serviceModel> 
    <bindings> 
     <basicHttpBinding> 
     <binding name="BasicHttpBinding_IService" closeTimeout="01:01:00" 
      openTimeout="01:01:00" receiveTimeout="01:10:00" sendTimeout="01:01:00" 
      allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" 
      maxBufferSize="2147483647" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" 
      messageEncoding="Text" textEncoding="utf-8" transferMode="Streamed" 
      useDefaultWebProxy="true"> 
      <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" 
      maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" /> 
      <security mode="None"> 
      <transport clientCredentialType="None" proxyCredentialType="None" 
       realm="" /> 
      <message clientCredentialType="UserName" algorithmSuite="Default"/> 
      </security> 
     </binding> 
     </basicHttpBinding> 

     <webHttpBinding> 
     <binding name="WebHttpBinding_IService" closeTimeout="01:01:00" openTimeout="01:01:00" 
      receiveTimeout="01:10:00" sendTimeout="01:01:00" allowCookies="false" 
      bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" 
      maxBufferSize="2147483647" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" 
      transferMode="Streamed" useDefaultWebProxy="true"> 
      <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" 
      maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" /> 
      <security mode="None" /> 
     </binding> 
     <binding name="webHttpBindingXML"/> 
     <binding name="webHttpBindingJSON"/> 
     </webHttpBinding> 
    </bindings> 

    <services> 
     <service name="SearchService.SearchService" behaviorConfiguration="ServiceBehaviour"> 
     <!-- Service Endpoints --> 
     <!-- Unless fully qualified, address is relative to base address supplied above --> 
     <endpoint address ="" binding="webHttpBinding" bindingConfiguration="WebHttpBinding_IService" contract="SearchService.ISearchService" behaviorConfiguration="web"> 
      <!-- 
       Upon deployment, the following identity element should be removed or replaced to reflect the 
       identity under which the deployed service runs. If removed, WCF will infer an appropriate identity 
       automatically. 
      --> 
     </endpoint> 
     </service> 
    </services> 

    <behaviors> 
     <serviceBehaviors> 
     <behavior name="ServiceBehaviour"> 
      <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment --> 
      <serviceMetadata httpGetEnabled="true"/> 
      <!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information --> 
      <serviceDebug includeExceptionDetailInFaults="true"/> 
     </behavior> 
     </serviceBehaviors> 
     <endpointBehaviors> 
     <behavior name="web"> 
      <webHttp/> 
     </behavior> 
     </endpointBehaviors> 
    </behaviors> 

    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" /> 

    <standardEndpoints> 
     <webHttpEndpoint> 
     <standardEndpoint 
      automaticFormatSelectionEnabled="true" 
      helpEnabled="true" /> 
     </webHttpEndpoint> 
    </standardEndpoints> 
    </system.serviceModel> 

<system.webServer> 
    <modules runAllManagedModulesForAllRequests="true"/> 
    </system.webServer> 

</configuration> 

Объект запроса формируется таким образом

[DataContract] 
public class Query 
{ 
    [DataMember] 
    public string name { get; set; } 

    [DataMember] 
    public string birthDate { get; set; } 
} 

[DataContract] 
public class Input 
{ 
    [DataMember] 
    public Query query { get; set; } 

    [DataMember] 
    public string login_username { get; set; } 

    [DataMember] 
    public string login_password { get; set; } 
} 

[DataContract] 
public class Request 
{ 
    [DataMember] 
    public Input input { get; set; } 
} 

Я создал небольшой клиент для проверки этого запроса, и я также проверил его, используя WCFTestClient и ks штраф. Если я попытаюсь получить доступ к этому через скрипач, хотя получаю ошибку 415 Unsupported Media Type.

Я попытался это следующим образом

POST, http://localhost:8080/HostDevServer/SearchService.svc/json, HTTP/1.1 

User-Agent: Fiddler 
Content-Type: application/json;charset=UTF-8 
Host: localhost:8080 
Content-Length: 368 

{ "input": { "login_password": "pass", "login_username": "login name", "query": { "birthDate": "", "name": "robert" } } } 

Я также попытался развернуть эту услугу, и посмотреть, если стелька сможет получить к нему доступ тогда, но все стало еще более запутанным, потому что теперь вместо того, чтобы получить 415 I получал сообщение , жалующийся на 'Reference to an object not set to an instance of the object.', и небольшой клиент командной строки, который я создал, будет жаловаться на то, что я установил There was no endpoint listening at местоположение моего сервиса.

Мой вопрос: есть ли что-то не так с моим конфигурационным файлом или я не скомпоновал запрос на скрипач? Если да, то как я могу исправить это, чтобы я мог нормально пользоваться моей службой?

ответ

3

Я вижу, что вы используете BodyStyle = WebMessageBodyStyle.Wrapped

Это означает, что вам нужно обернуть фактические данные с именем переменной ожидаемой вашей OperationContract. Короче говоря, это должно работать

{ "response": { "input": { "login_password": "pass", "login_username": "login name", "query": { "birthDate": "", "name": "robert" } } } } 

Если вы хотите сохранить содержимое тела как то я предлагаю вам использовать Bare вместо Wrapped для стиля тела.

+1

@Tim спасибо за редактирование, иногда мои руки пишут сами по себе. – ealiaj