2012-10-30 87 views
2

我在使用ServiceStack進行網絡服務。預計標題是:Consuming Web Service HTTP Post

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<LogsDTOResponse>(URI + "/SeizureAPILogs", logs); 
    } 
} 

我無法弄清楚如何序列化的DTO前添加jsonRequest=。我該怎麼做呢?

解決方案基於Mythz的回答

新增如何我用Mythz的回答爲那些具有在未來同樣的問題(S)的人 - 享受!

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<LogsDTOResponse>(); 
} 

回答

3

這是一個很奇怪的使用定製服務客戶端發送x-www-form-urlencoded數據,我認爲這是一個雄心勃勃的一點嘗試爲ServiceStack的ServiceClients是爲了發送/接收相同的內容類型。儘管你的班級被稱爲JsonCustomClient,但它不再是JSON客戶端,因爲你已經覆蓋了Format屬性。

您的問題很可能在使用語句中使用StreamWriter,該語句會關閉底層流。此外,我希望你調用基本方法是一個錯誤,因爲你將有一個非法的網址編碼+ JSON內容類型的混合。

就我個人而言,我會避開ServiceClients,只使用任何標準的HTTP客戶端,例如ServiceStack有一些extensions to WebRequest一個封裝中進行HTTP要求通常與樣板.NET調用,如:

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

var logsDtoResponse = json.FromJson<LogsDTOResponse>(); 
+0

感謝Mythz,我想留清楚,但消費的web請求的複雜性讓我想嘗試和數字它與ServiceStack一起出來。我很高興你有這些擴展,真的很感激。 –