【问题标题】:WCF REST service POST methodWCF REST 服务 POST 方法
【发布时间】:2012-02-04 15:21:15
【问题描述】:

我需要创建一个带有 4 个字符串参数的 POST 方法的 REST 服务

我定义如下:

[WebInvoke(UriTemplate = "/", Method = "POST", BodyStyle= WebMessageBodyStyle.WrappedRequest)]
public Stream ProcessPost(string p1, string p2, string p3, string p4)
{
    return Execute(p1, p2, p3, p4);
}

我想用如下代码调用它:

        string result = null;
        HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest;
        req.Method = "POST";
        req.ContentType = "application/x-www-form-urlencoded";

        string paramz = string.Format("p1={0}&p2={1}&p3={2}&p4={3}", 
            HttpUtility.UrlEncode("str1"),
            HttpUtility.UrlEncode("str2"),
            HttpUtility.UrlEncode("str3"),
            HttpUtility.UrlEncode("str4")
            );

        // Encode the parameters as form data:
        byte[] formData =
            UTF8Encoding.UTF8.GetBytes(paramz);
        req.ContentLength = postData.Length;

        // Send the request:
        using (Stream post = req.GetRequestStream())
        {
            post.Write(formData, 0, formData.Length);
        }

        // Pick up the response:
        using (HttpWebResponse resp = req.GetResponse()
                                      as HttpWebResponse)
        {
            StreamReader reader =
                new StreamReader(resp.GetResponseStream());
            result = reader.ReadToEnd();
        }

        return result;

但是,客户端代码返回代码 400:错误请求

我做错了什么?

谢谢

【问题讨论】:

  • 尝试打开 WCF 跟踪以查看问题所在,但我认为服务需要 XML

标签: wcf rest post


【解决方案1】:

我会说不支持 form-urleconded 格式。 WebInvoke 属性的 RequestFormat 属性是 WebMessageFormat 枚举类型,它只将 JSON 和 XML 定义为有效格式。

http://msdn.microsoft.com/en-us/library/system.servicemodel.web.webmessageformat.aspx

【讨论】:

    【解决方案2】:

    我想说在UriTemplate 中声明参数,如下所示

    [OperationContract]
    [WebInvoke(UriTemplate = "{p1}/{p2}/{p3}/{p4}", Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest)]
    string ProcessPost(string p1, string p2, string p3, string p4);
    

    并使用下面的代码来调用,

    string result = null; 
    string uri = "http://localhost:8000/ServiceName.svc/1/2/3/4";
    
    HttpWebRequest req = WebRequest.Create(uri) as HttpWebRequest;
    req.KeepAlive = false;
    req.Method = "POST";
    
    using (HttpWebResponse resp = req.GetResponse() as HttpWebResponse) 
       { 
           StreamReader reader = new StreamReader(resp.GetResponseStream()); 
           result = reader.ReadToEnd(); 
       }
    

    它对我来说很好用。希望这种方法对您有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多