【问题标题】:c# Passing an object to a REST enabled WCF Servicec# 将对象传递给启用了 REST 的 WCF 服务
【发布时间】:2015-02-04 16:28:43
【问题描述】:

我正在尝试将自定义对象和 2 个字符串值传递给启用了 REST 和 SOAP 的 WCF 服务

以下是服务合同

[OperationContract]
     [WebInvoke(UriTemplate = "/AddData/{Name}/{Id}", RequestFormat = WebMessageFormat.Json,
            ResponseFormat = WebMessageFormat.Json, Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped )]
           bool AddData(CustomData itm,string Name, string Id);

然后我有示例代码尝试使用 HTTP Client 调用服务,我遇到的问题是字符串值被传入但对象值为 null

我不确定我是否定义了错误的服务或调用了错误的服务?

private async void button1_Click(object sender, EventArgs e)
    {
        try
        {
 var client = new HttpClient();
            var uri = new Uri("http://localhost:52309/Service1.svc/rest/AddData/test/1");

            CustomData data = new  CustomData ();
            data.description = "TEST";
            data.fieldid = "test1";
            data.fieldvalue = "BLA";

            string postBody = JsonSerializer(data);

            HttpContent contentPost = new StringContent(postBody , Encoding.UTF8, "application/json");
            HttpResponseMessage wcfResponse = await client.PostAsync(uri, contentPost).ContinueWith((postTask) => postTask.Result.EnsureSuccessStatusCode());


            client.Dispose();
 string responJsonText = await wcfResponse.Content.ReadAsStringAsync();

 }
        catch (Exception ex)
        {

        }
}

public string JsonSerializer(FormsData  objectToSerialize)
    {
        if (objectToSerialize == null)
        {
            throw new ArgumentException("objectToSerialize must not be null");
        }
        MemoryStream ms = null;

        DataContractJsonSerializer serializer = new DataContractJsonSerializer(objectToSerialize.GetType());
        ms = new MemoryStream();
        serializer.WriteObject(ms, objectToSerialize);
        ms.Seek(0, SeekOrigin.Begin);
        StreamReader sr = new StreamReader(ms);
        return sr.ReadToEnd();
    }

【问题讨论】:

  • 消息正文是否应该包含格式为 JSON 的CustomData?如果是这样,类型需要是 Stream 然后你反序列化它。
  • 是的,我想我正在尝试将对象格式化为 JSON,您介意详细说明一下,类型需要流式传输吗?
  • 你看过使用PostAsJsonAsync<T>吗?
  • 当然,除非CustomData 对象有某种反序列化步骤,例如DataContract
  • @RachaelM 抱歉,我的意思是链接PostAsync<T>,这样您就可以直接发布对象,而无需先转换为 Json。

标签: c# web-services wcf rest dotnet-httpclient


【解决方案1】:

我通过添加解决了这个问题 [DataContract(Namespace = "CustomData")][DataMember(Name = "fieldvalue")] 到类定义中的每个变量,然后使用 PostAsJsonAsync 调用它并直接传递对象。感谢@DanielPark 和@DavidG 提供正确方向的指示

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-04
    • 2014-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多