使用 httpclient postAsJsonAsync 来自 WCF 服务的错​​误请求

Bad Request from WCF Service using httpclient postAsJsonAsync

以下是我的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; }
}

当我通过以下方式调用上述服务时,我总是收到 Bad Request Error。

          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;

见下图。

你能指出我在这里做错了什么吗?

试试这个,更改 UriTemplate

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

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

试试这个 'BodyStyle = WebMessageBodyStyle.WrappedRequest',

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

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