使用Web服务HTTP Post

我正在使用ServiceStack来使用Web服务。 标题是:

POST /SeizureWebService/Service.asmx/SeizureAPILogs HTTP/1.1 Host: host.com Content-Type: application/x-www-form-urlencoded Content-Length: length jsonRequest=string 

我正在尝试使用此代码使用它:

 public class JsonCustomClient : JsonServiceClient { public override string Format { get { return "x-www-form-urlencoded"; } } public override void SerializeToStream(ServiceStack.ServiceHost.IRequestContext requestContext, object request, System.IO.Stream stream) { string message = "jsonRequest="; using (StreamWriter sw = new StreamWriter(stream, Encoding.Unicode)) { sw.Write(message); } // I get an error that the stream is not writable if I use the above base.SerializeToStream(requestContext, request, stream); } } public static void JsonSS(LogsDTO logs) { using (var client = new JsonCustomClient()) { var response = client.Post(URI + "/SeizureAPILogs", logs); } } 

我无法弄清楚如何在序列化DTO之前添加jsonRequest= 。 我该怎么做呢?

解决方案基于Mythz的答案

添加了我如何使用Mythz的答案为将来有同样问题的人 – 享受!

 public static LogsDTOResponse JsonSS(LogsDTO logs) { string url = string.Format("{0}/SeizureAPILogs", URI); string json = JsonSerializer.SerializeToString(logs); string data = string.Format("jsonRequest={0}", json); var response = url.PostToUrl(data, ContentType.FormUrlEncoded, null); return response.FromJson(); } 

这是一个非常奇怪的使用自定义服务客户端发送x-www-form-urlencoded数据,我认为这有点野心,因为ServiceStack的ServiceClients旨在发送/接收相同的Content-type。 即使您的类被称为JsonCustomClient它也不再是JSON客户端,因为您已经覆盖了Format属性。

你有的问题可能是在一个将关闭底层流的using语句中使用StreamWriter 。 此外,我希望您将基本方法称为错误,因为您将在线路上非法混合使用Url-Encoded + JSON内容类型。

我个人会避开ServiceClients并只使用任何标准HTTP客户端,例如ServiceStack有一些WebRequest扩展,它包含了用.NET进行HTTP调用所需的通常样板,例如:

 var json = "{0}/SeizureAPILogs".Fmt(URI) .PostToUrl("jsonRequest=string", ContentType.FormUrlEncoded); var logsDtoResponse = json.FromJson();