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

赫连正初
2023-12-01


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();
    }
  }

 类似资料: