在post wcf服务中获取空值

时间:2013-06-05 06:24:06

标签: wcf web-services rest wcf-data-services

我正在写一个WCF服务。这是服务端实现

    [OperationContract(Name="GetMediaFile")]
    [Description(ServiceDescConstants.GetMediaFile)]
    [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = UriTemplateConstants.GetMediaFile)]        
    Stream GetMediaFile(string type, string mediaId);

其中

UriTemplateConstants.GetMediaFile = "GetMediaFile?type={type}&mediaId={mediaId}";

这是接口方法实现

  public Stream GetMediaFile(string type, string mediaId)
    {
            CustomerBL customerBl = new CustomerBL();
            return customerBl.getMediaFile(Convert.ToInt32(type), Convert.ToInt32(mediaId));            
    }

在客户端,我使用RestClient插件来测试服务。 这是我发送的数据

网址:customersite / GetMediaFile 标题:Content-Type = x-www-form-urlencoded 正文:type = 0& mediaId = 1

任何帮助!!

现在问题是我得到空值

1 个答案:

答案 0 :(得分:2)

修改界面方法:

[OperationContract(Name = "GetMediaFile")]
[Description(ServiceDescConstants.GetMediaFile)]
[WebInvoke(Method = "POST", 
    ResponseFormat = WebMessageFormat.Json, 
    BodyStyle = WebMessageBodyStyle.Wrapped, 
    UriTemplate = "/GetMediaFile")]
Stream GetMediaFile(Stream input);

并修改它的实施:

public Stream GetMediaFile(Stream input)
{
    StreamReader sr = new StreamReader(input);
    string s = sr.ReadToEnd();
    sr.Dispose();
    NameValueCollection qs = HttpUtility.ParseQueryString(s);
    string type = qs["type"];
    string mediaId = qs["mediaId"];

    CustomerBL customerBl = new CustomerBL();
    return customerBl.getMediaFile(Convert.ToInt32(type), Convert.ToInt32(mediaId));
}

web.config 中,使用以下配置(确保使用自己的命名空间/类/接口名称):

<system.serviceModel>
  <services>
    <service name="WcfServices.MyService">
      <endpoint address="" 
                name="webEndPoint" 
                behaviorConfiguration="webBehavior"
                binding="webHttpBinding" 
                contract="WcfServices.IMyService" />
    </service>
  </services>
  <behaviors>
    <endpointBehaviors>
      <behavior name="webBehavior">
        <webHttp />
      </behavior>
    </endpointBehaviors>
  </behaviors>
</system.serviceModel>

这是一个示例请求:

POST /MyService.svc/GetMediaFile HTTP/1.1
Host: localhost:64531
Cache-Control: no-cache
Content-Type: application/x-www-form-urlencoded

type=0&mediaId=1

该解决方案改编自Edgardo Rossetto的博客文章Raw HTTP POST with WCF