servicestack,C#,Http Post,servicestack" /> servicestack,C#,Http Post,servicestack" />

C# 使用Web服务HTTP Post

C# 使用Web服务HTTP Post,c#,http-post,servicestack,C#,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 : JsonServiceClien

我正在使用一个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<LogsDTOResponse>(URI + "/SeizureAPILogs", logs);
    }
}

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

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

就个人而言,我会避开ServiceClient,只使用任何标准HTTP客户端,例如ServiceStack有一些封装了使用.NET进行HTTP调用所需的常用样板文件,例如:

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

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

谢谢Mythz,我想保持清醒,但使用web请求的复杂性让我想尝试使用ServiceStack解决这个问题。我很高兴你有这些扩展,非常感谢。
var json = "{0}/SeizureAPILogs".Fmt(URI)
           .PostToUrl("jsonRequest=string", ContentType.FormUrlEncoded);

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