使用httpclient postAsJsonAsync从WCF服务收到错误请求

时间:2015-07-14 06:55:35

标签: c# wcf httpclient

以下是我的wcf服务。

  public ApiResponseWrapper<TextBlobModel> PostText(string sessionId, string profileId, TextBlobModel txtModel)
    {}

接口部分是

 [OperationContract]
    [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "session/{sessionId}/profile/{profileId}/text")]
    ApiResponseWrapper<TextBlobModel> PostText(string sessionId, string profileId, TextBlobModel txtModel);

模特是

 [DataContract]
public class TextBlobModel
{
    [DataMember]
    public string text { get; set; }

   [DataMember]
    public DateTime receivedTime { get; set; }
}

当我通过以下方式调用上述服务时,我总是收到错误请求错误。

          var baseApiUrl = "http://localhost:51398/api.svc/";
           HttpClient authClient = new HttpClient();
           authClient.BaseAddress = new Uri(baseoAuthApiUrl);
           apiClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

           var txtModel = new TextBlobModel();
           txtModel.text = "Hello How are you";
           txtModel.receivedTime = DateTime.Now;

            HttpResponseMessage txtResponse = apiClient.PostAsJsonAsync(String.Format("session/{0}/profile/{1}/text", "sessionId", "profileId"), txtModel).Result;
            var txtData = txtResponse.Content.ReadAsAsync<RootObject>().Result;

见下图。

enter image description here

你能否在这里建议我做错了什么?

1 个答案:

答案 0 :(得分:1)

试试这个,改变UriTemplate

"session/{sessionId}/profile/{profileId}/text"

"PostText/session/{sessionId}/profile/{profileId}/text".

试试这个&#39; BodyStyle = WebMessageBodyStyle.WrappedRequest&#39;,

并将其添加到配置文件以添加跟踪日志,之后您将收到实际错误。

<configuration> 
<system.diagnostics>
<trace autoflush="true">
</trace> 
<sources> 
<source name="System.ServiceModel" switchValue="Critical,Information,ActivityTracing" propagateActivity="true">
<listeners> 
<add name="sdt" type="System.Diagnostics.XmlWriterTraceListener" initializeData="C:\logs\messages.svclog" />
</listeners>
</source> 
</sources> 
</system.diagnostics>
</configuration>