2

我正在使用ServiceStack使用网络服务。预期的标题是:

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

我不知道如何jsonRequest=在序列化 DTO 之前添加。我该怎么做呢?

基于神话的答案的解决方案

添加了我如何为将来遇到相同问题的人使用 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<LogsDTOResponse>();
}
4

1 回答 1

3

这是使用自定义服务客户端发送x-www-form-urlencoded数据的一种非常奇怪的用法,我认为尝试这样做有点雄心勃勃,因为 ServiceStack 的 ServiceClients 旨在发送/接收相同的内容类型。即使您的类被调用JsonCustomClient,它也不再是 JSON 客户端,因为您已经覆盖了该Format属性。

The issue your having is likely using the StreamWriter in a using statement which would close the underlying stream. Also I expect you calling the base method to be an error since you're going to have an illegal mix of Url-Encoded + JSON content-type on the wire.

Personally I would steer clear of the ServiceClients and just use any standard HTTP Client, e.g. ServiceStack has some extensions to WebRequest that wraps the usual boilerplate required in making HTTP calls with .NET, e.g:

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

var logsDtoResponse = json.FromJson<LogsDTOResponse>();
于 2012-10-30T22:51:33.830 回答