将json字符串发送到restful wcf - 远程服务器返回错误:(400)错误请求

时间:2016-12-08 12:38:19

标签: c# asp.net json rest wcf

我创建了restful wcf:

<OperationContract()> _
    <WebInvoke(Method:="POST", UriTemplate:="/getlatestbill", BodyStyle:=WebMessageBodyStyle.Bare, RequestFormat:=WebMessageFormat.Json, ResponseFormat:=WebMessageFormat.Json)> _
    Function getlatestbill(ByVal usrinfo As String) As String

我已经看到很多 POST Restful WCF 与ContentXml或类的链接,但我想传递 JsonString 。在上面的代码中,我将userinfo作为 json String 传递,其中包含id和city。如

Sub Post()
        Dim req As HttpWebRequest = Nothing
        Dim res As HttpWebResponse = Nothing
        Try
            Dim strg As String
            strg = New JavaScriptSerializer().Serialize(New With {Key .ID = 1, Key .city = "dehradun"})
            Const url As String = "http://localhost:1843/mobsrv.svc/getlatestbill"
            req = CType(WebRequest.Create(url), HttpWebRequest)
            req.Method = "POST"
            req.ContentType = "application/json; charset=utf-8"
            req.Timeout = 30000
            'req.Headers.Add("SOAPAction", url)

            req.ContentLength = strg.Length
            Dim sw = New StreamWriter(req.GetRequestStream())
            sw.Write(strg)
            sw.Close()

            res = CType(req.GetResponse(), HttpWebResponse)
            Dim responseStream As Stream = res.GetResponseStream()
            Dim streamReader = New StreamReader(responseStream)

         Catch ex As Exception
            Response.Write(ex.Message)
        End Try
    End Sub

将json字符串传递给服务时,其 res.GetResponseStream()中的抛出错误为:

  

远程服务器返回错误:(400)错误请求。

我看过很多SO帖子,但是他们都没有在post函数中接受jsonString。

如何通过 POST json String 传递给wcf restful服务?

0 个答案:

没有答案