简体   繁体   中英

request addparameter array but return empty in response

I use RestSharp.

I have a list private List<string> _GuyIds; Then

        [TestMethod]
    public void GuyMetadataServiceShouldReturnExpected()
    {
        var client = new RestClient("http://localhost/OrionServices/GuyService.svc/");

        var request = new RestRequest("{facilityId}/Guys/metadata/", Method.POST);
        request.AddUrlSegment("facilityId", "888");
        request.AddParameter("GuyIds", JsonConvert.SerializeObject(_GuyIds.ToArray()), ParameterType.RequestBody);

        var response = client.Execute(request);
        dynamic data = JsonConvert.DeserializeObject<dynamic>(response.Content);

In the service,

        [OperationContract]
    [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedResponse, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "/{FacilityID}/Guys/metadata/")]
    public List<dynamic> GenerateMetadata(string FacilityID)
    {
        WebOperationContext.Current.OutgoingResponse.Headers.Add("Cache-Control", "no-cache, must-revalidate");
        WebOperationContext.Current.OutgoingResponse.Headers.Add("Expires", "Sat, 26 Jul 1997 05:00:00 GMT");

        var Guys = Encoding.UTF8.GetString(OperationContext.Current.RequestContext
            .RequestMessage.GetBody<byte[]>());

When I hover over the Guys in the service code, I got

["0001","0003","0004","0005","0006"]

However when I check the response, the content is empty. I guess that something wrong when I passed the array to the request in this line.

request.AddParameter("GuyIds", JsonConvert.SerializeObject(_GuyIds.ToArray()), ParameterType.RequestBody);

How to fix it?

Figure it out by myself. WCF doesn't support serializing dynamic type. I have to define a POCO object.

   [OperationContract]
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedResponse, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "/{FacilityID}/Guys/metadata/")]
public List<GuysDTO> GenerateMetadata(string FacilityID)
{
    WebOperationContext.Current.OutgoingResponse.Headers.Add("Cache-Control", "no-cache, must-revalidate");
    WebOperationContext.Current.OutgoingResponse.Headers.Add("Expires", "Sat, 26 Jul 1997 05:00:00 GMT");

Then

public class GuyDTO
{
     public string metadata1 {get;set;}
      ....
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM