Чтение содержимого запроса в форме JSON из OperationContext в C#

Я создал WCF RESTful сервис, как показано ниже:

[OperationContract]
[WebInvoke(Method = "PUT",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/Customer/{customerID}/profile")]
string PutCustomerProfileData(string customerID);

Я отлаживаю это с помощью Postman и передаю данные JSON в BODY, как показано ниже:

{"customerID": "RC0064211", "TermsAgreed": "true"}

public string PutCustomerProfileData(string customerID)
{
    Message requestMessage = OperationContext.Current.RequestContext.RequestMessage;
}

Что он возвращает в RequestMessage, как показано ниже:

{<root type="object">
  <customerID type="string">RC0064211</customerID>
  <TermsAgreed type="string">true</TermsAgreed>
</root>}

Я хочу это тело запроса в форме JSON. Могу ли я получить это? Если нет, то какой другой способ я могу создать строку JSON для упомянутых RequestMessage?

3 ответа

Решение

Я пробовал с DataContract а также DataMember и это сработало для меня.

Ниже приведен пример кода:

[OperationContract]
    [WebInvoke(Method = "PUT",
        RequestFormat = WebMessageFormat.Json,
        ResponseFormat = WebMessageFormat.Json,
        UriTemplate = "/Customer/{customerID}/verification")]
    string PutCustomerVerificationData(string customerID, CustomerVerification customerVerification);
}

[DataContract]
public class CustomerVerification
{
    [DataMember]
    public string PasswordHash { get; set; }

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

Затем я преобразовал этот DataContract в строку JSON и использовал его далее, как показано ниже:

public string PutCustomerVerificationData(string customerID, CustomerVerification customerVerification)
{
      JavaScriptSerializer js = new JavaScriptSerializer();
      string requestBody = js.Serialize(customerVerification);
      string serviceResponse = bllCustomerDetails.PutCustomerVerificationData(customerID, requestBody).Replace("\"", "'");
      return serviceResponse;
}

Добавьте [DataMember] поверх переменных-членов, которые вы хотите преобразовать в JSON.

Я на самом деле не до конца понял проблему, но в качестве рекомендации могу предложить;

Вы должны разработать свой WebConfig для Json следующим образом;

    <services>
  <service name="Your Service Name"

    <endpoint address="" behaviorConfiguration="webHttp" binding="webHttpBinding"
              bindingConfiguration="webHttpBindingWithJsonP" contract="YourProjectName">

    </endpoint>
  </service>
</services>
<bindings>
  <webHttpBinding>
    <binding name="webHttpBindingWithJsonP" />

             </binding>
  </webHttpBinding>
</bindings>


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

И вашему члену данных должно понравиться это (только пример);

   [DataContract]
public class Customer
{
   [DataMember]
    public int ID { get; set; }

    [DataMember]
    public int customerID { get; set; }

}

Кроме того, вы можете примерить свой веб-сервис на Fiddler 4, и вы можете запрашивать и отвечать как JSON или как хотите.

Другие вопросы по тегам