【问题标题】:Consuming Web Service HTTP Post使用 Web 服务 HTTP Post
【发布时间】:2012-10-30 20:24:07
【问题描述】:

我正在使用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);
    }
}

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

基于神话答案的解决方案

添加了我如何将 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>();
}

【问题讨论】:

    标签: c# http-post servicestack


    【解决方案1】:

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

    您遇到的问题可能是在 using 语句中使用 StreamWriter 会关闭底层流。另外,我希望您调用基本方法是一个错误,因为您将在网络上非法混合 Url-Encoded + JSON 内容类型。

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

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

    【讨论】:

    • 感谢 Mythz,我想保持清楚,但使用 Web 请求的复杂性让我想尝试使用 ServiceStack 来解决这个问题。我很高兴你有这些扩展,真的很感激。
    猜你喜欢
    • 1970-01-01
    • 2010-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多