Using x-www-form-urlencoded Content-Type in WCF

17 篇文章 0 订阅


So we have a wcf restful web service configured with webHttpBinding and everything works fine with http get.  If change it to Post and post something like variable1=1&variable2=2 in message body doesn't pick up the parameters.  Is it possible to configure this to work in this situation?


To use the Stream format, you'd need to change your operation signature, as in the example below. With the new HTTP model (available in wcf.codeplex.com, and likely in the next version of the framework) you should be able to do it in a more elegant way.


public class Post_12293ed1_e89d_4376_8888_3d89896b5582
  {
    [ServiceContract]
    public interface ITest
    {
      [OperationContract]
      void Process(Stream data);
    }
    public class Service : ITest
    {
      public void Process(Stream data)
      {
        string strData = new StreamReader(data).ReadToEnd();
        NameValueCollection nvc = HttpUtility.ParseQueryString(strData);
        var username = nvc["username"];
        var password = nvc["password"];
        Console.WriteLine("User: {0}; password: {1}", username, password);
      }
    }
    public static void Test()
    {
      string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
      ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress));
      WebHttpBinding binding = new WebHttpBinding();
      host.AddServiceEndpoint(typeof(ITest), binding, "").Behaviors.Add(new WebHttpBehavior());
      host.Open();
      Console.WriteLine("Host opened");

      string request = "username=John%20Doe&password=MySecretWord";

      WebClient client = new WebClient();
      client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
      client.UploadString(baseAddress + "/Process", "POST", request);

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值