通过post发送的wcf服务消费表单数据

时间:2011-08-29 09:01:11

标签: asp.net wcf forms post

我阅读了一些关于此的文章,我发现要获得wcf从发布请求中获取数据我们添加

[ServiceContract]
public interface IService1 {
  [OperationContract]
  [WebInvoke(
      Method = "POST",
      BodyStyle = WebMessageBodyStyle.Bare,
      UriTemplate = "/GetData")]
  void GetData(Stream data);
}

并在实施中

public string GetData( Stream input)
{
    long incomingLength = WebOperationContext.Current.IncomingRequest.ContentLength;
    string[] result = new string[incomingLength];
    int cnter = 0;
    int arrayVal = -1;
    do
    {
        if (arrayVal != -1) result[cnter++] = Convert.ToChar(arrayVal).ToString();
        arrayVal = input.ReadByte();
    } while (arrayVal != -1);

    return incomingLength.ToString();
}

我的问题是我应该怎么做才能在表单请求中将提交操作发送到我的服务并消费?

在Stream参数中,我是否可以通过Request [“FirstName”]从表单中发布信息?

1 个答案:

答案 0 :(得分:12)

您的代码未正确解码请求正文 - 您正在创建一个string值数组,每个值都包含一个字符。获取请求主体后,您需要解析查询字符串(使用HttpUtility是一种简单的方法)。下面的代码显示了如何正确获取正文和其中一个字段。

public class StackOverflow_7228102
{
    [ServiceContract]
    public interface ITest
    {
        [OperationContract]
        [WebInvoke(
            Method = "POST",
            BodyStyle = WebMessageBodyStyle.Bare,
            UriTemplate = "/GetData")]
        string GetData(Stream data);
    }
    public class Service : ITest
    {
        public string GetData(Stream input)
        {
            string body = new StreamReader(input).ReadToEnd();
            NameValueCollection nvc = HttpUtility.ParseQueryString(body);
            return nvc["FirstName"];
        }
    }
    public static void Test()
    {
        string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
        WebServiceHost host = new WebServiceHost(typeof(Service), new Uri(baseAddress));
        host.Open();
        Console.WriteLine("Host opened");

        WebClient c = new WebClient();
        c.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
        Console.WriteLine(c.UploadString(baseAddress + "/GetData", "FirstName=John&LastName=Doe&Age=33"));

        Console.Write("Press ENTER to close the host");
        Console.ReadLine();
        host.Close();
    }
}