使用不带DataContract的多个参数的WCF REST服务 [英] Consuming WCF REST Service with multiple parameters WITHOUT DataContract

查看:95
本文介绍了使用不带DataContract的多个参数的WCF REST服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用POST方法调用具有多个参数的WCF REST服务,但是由于我需要简单的类型,因此无法创建包含参数的DataContract:我的Web服务将由目标C应用程序使用.

I need to call my WCF REST Service with multiple parameters with the POST method, but I can't create DataContract containing my parameters because I need simple types : my webservice will be consumed by an objective C application.

我在MSDN站点上发现了这种语法:

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);

为了快速解释上下文,我必须调用此方法来保存带有在数据库中传递的ID的JSON文件.

To explain quickly the context, I have to call this method to save a JSON file with the Id passed on a database.

我的第一个问题是:是否真的有可能像之前所示将多个参数传递给POST方法?

My fisrt question is : is it really possible to pass several parameters to a POST method as shown before ?

第二:如何使用几个参数来使用我的服务(目前仅在C#中进行测试)?

Secondly : how can I do to consume my service (in C# for the moment, just to test it) with several parameters ?

我已经使用DataContract进行了测试,并且我正在这样做:

I've already tested with DataContract, and I was doing like that :

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和ResponseData是以这种方式声明的:

RequestData and ResponseData were declared this way :

[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 it like this anymore...

我希望我已经足够清楚了,如果没有的话,请随时向我询问细节!

I hope I'm enough clear, if not, don't hesitate to ask me details !

非常感谢您的帮助.

推荐答案

您可以采取一些措施来避免使用数据协定.其中最简单的方法是使用JSON DOM库,该库使您可以将(树)JSON数据创建(并解析为树),而不必将其转换为现有类.其中两个是JSON.NET项目(在下面的示例代码中使用)或System.Json库(可以通过NuGet下载).还有许多用于非.NET语言的JSON库.

There are a few things you can do to avoid using data contracts. The simplest of them is to use a JSON DOM library which lets you create (and parse) JSON data as a tree, without having to convert them to existing classes. Two of them are the 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 as well.

您可以简化生活的另一件事是将操作的主体样式从Wrapped(包装响应)更改为Wrapped到WrappedRequest.该请求需要包装,因为您有两个输入,但没有响应,因此您可以省去一个步骤.

Another thing you can do to make your life simpler is to change the body style of the operation from Wrapped (which wraps the response) to Wrapped to WrappedRequest. The request needs to be wrapped, since you have two inputs, but the response doesn't, 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();
    }
}

这篇关于使用不带DataContract的多个参数的WCF REST服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆