Consuming WCF REST Service with Multiple Parameters WITHOUT DataContract

I need to call a WCF REST service with multiple parameters using the POST method, but I cannot create a DataContract containing my parameters because I need simple types: my web service will be consumed by an object C application.

I found this syntax on the MSDN site:

[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "savejson?id={id}&fichier={fichier}")]
bool SaveJSONData(string id, string fichier);

      

To quickly explain the context, I have to call this method to save the JSON file with the ID passed in the database.

My question is, is it really possible to pass multiple parameters to the POST method as shown earlier?

Second: How do I go about using my service (in C # at the moment to test it) with multiple parameters?

I already tested DataContract and I did like this:

string url = "http://localhost:62240/iECVService.svc/savejson";
        WebClient webClient = new WebClient();
        webClient.Headers["Content-type"] = "application/json; charset=utf-8";
        RequestData reqData = new RequestData { IdFichier = "15", Fichier = System.IO.File.ReadAllText(@"C:\Dev\iECV\iECVMvcApplication\Content\fichier.json") };
        MemoryStream requestMs = new MemoryStream();
        DataContractJsonSerializer requestSerializer = new DataContractJsonSerializer(typeof(RequestData));
        requestSerializer.WriteObject(requestMs, reqData);
        byte[] responseData = webClient.UploadData(url, "POST", requestMs.ToArray());
        MemoryStream responseMs = new MemoryStream(responseData);
        DataContractJsonSerializer responseSerializer = new DataContractJsonSerializer(typeof(ResponseData));
        ResponseData resData = responseSerializer.ReadObject(responseMs) as ResponseData;

      

RequestData and ResponseData were declared like this:

[DataContract(Namespace = "")]
public class RequestData
{
    [DataMember]
    public string IdFichier { get; set; }

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

[DataContract]
public class ResponseData
{
    [DataMember]
    public bool Succes { get; set; }
}

      

But as I said, I can't do this anymore ...

I hope I'm clear enough, if not, feel free to ask for details!

Many thanks for your help.

+3


source to share


1 answer


There are several things you can do to avoid using data contracts. The simplest one is to use the JSON DOM library, which allows you to create (and parse) JSON data as a tree without having to convert it to existing classes. Two of them are a JSON.NET project (used in the sample code below) or the System.Json library (can be downloaded via NuGet). There are many JSON libraries for non-.NET languages.

Another thing you can do to make life easier is change the style of the operation body from wrapped (which wraps the response) to Wrapped to WrappedRequest. The request needs to be wrapped since you have two inputs but there is no answer, so you can eliminate one step with that.



public class Post_182e5e41_4625_4190_8a4d_4d4b13d131cb
{
    [ServiceContract]
    public class Service
    {
        [OperationContract]
        [WebInvoke(Method = "POST",
            ResponseFormat = WebMessageFormat.Json,
            RequestFormat = WebMessageFormat.Json,
            BodyStyle = WebMessageBodyStyle.WrappedRequest,
            UriTemplate = "savejson")]
        public bool SaveJSONData(string id, string fichier)
        {
            return true;
        }
    }

    public static void Test()
    {
        string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
        WebServiceHost host = new WebServiceHost(typeof(Service), new Uri(baseAddress));
        host.Open();
        Console.WriteLine("Host opened");

        JObject json = new JObject();
        json.Add("id", JToken.FromObject("15"));
        json.Add("Fichier", "the file contents"); //System.IO.File.ReadAllText(@"C:\Dev\iECV\iECVMvcApplication\Content\fichier.json"));

        WebClient c = new WebClient();
        c.Headers[HttpRequestHeader.ContentType] = "application/json";
        string result = c.UploadString(baseAddress + "/savejson", json.ToString(Newtonsoft.Json.Formatting.None, null));
        JToken response = JToken.Parse(result);
        bool success = response.ToObject<bool>();
        Console.WriteLine(success);

        Console.Write("Press ENTER to close the host");
        Console.ReadLine();
        host.Close();
    }
}

      

+4


source







All Articles