Click here to Skip to main content
15,892,298 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
VS2012, WCF Rest Service, C#

I am trying to test a POST method of my WCF REST service, but get NULL in the service operation/method. Please help!

Note: All GET methods are successful and I am able to get the data in xml format.

Here is my Service Contract:
C#
[ServiceContract]
[XmlSerializerFormat]  // If I don't put this I get 400 - BAD Request error and it does not reach to service operation
public interface IRegionService
{
	[WebInvoke(UriTemplate = "regions", Method = "POST", 
	ResponseFormat = WebMessageFormat.Xml, RequestFormat=WebMessageFormat.Xml,
	BodyStyle=WebMessageBodyStyle.Wrapped)] // If I don't put BodyStyle other than Wrapped I get 400 - BAD Request error and it does not reach to service operation
	[OperationContract]
	int Add(RegionData objRegion);
}

[DataContract(Namespace="http://northwind.com/regions")]
public class RegionData
{
	[DataMember(IsRequired=true)]
	public int RegionID = 0;
	[DataMember(IsRequired = true)]
	public string RegionDescription = string.Empty;
}



Here is my Sevice Implementation:
C#
public class RegionService: IRegionService
{
	public int Add(RegionData objRegion)
        {
		// Received objRegion as NULL ???
            using (SqlConnection cn = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = new SqlCommand(SQL_ADD, cn))
                {
		cmd.CommandType = CommandType.Text;
		cmd.Parameters.AddWithValue("@RegionID", objRegion.RegionID);
		cmd.Parameters.AddWithValue("@RegionDescription", objRegion.RegionDescription);
		cn.Open();
		int rowsAffected = cmd.ExecuteNonQuery();
		return (int)cmd.Parameters["@RegionID"].Value;
                }
            }
        }
}


Here is App.Config:
XML
<system.serviceModel>
    <services>
      <service behaviorConfiguration="Default" name="RegionService">
        <endpoint address="" behaviorConfiguration="Web" binding="webHttpBinding"
          name="Web" contract="IRegionService" />
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8733/regionservice" />
          </baseAddresses>
        </host>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="Default">
          <serviceMetadata httpGetEnabled="True"/>
          <serviceDebug includeExceptionDetailInFaults="True" />
        </behavior>
      </serviceBehaviors>
		<endpointBehaviors>
			<behavior name="Web">
				<webHttp helpEnabled="true" automaticFormatSelectionEnabled="true" defaultOutgoingResponseFormat="Xml" />
			</behavior>
		</endpointBehaviors>
    </behaviors>
  </system.serviceModel>


Here is my client code:
C#
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("http://localhost:8733/regionservice/regions");
req.Method = "POST";
req.ContentType = "application/xml"; // get 400 - BAD Request error. However, If i set to null, it reaches the service operation but objRegion shows null in debug editor
if (body != null)
{
	byte[] bodyBytes = Encoding.UTF8.GetBytes(body);
	req.GetRequestStream().Write(bodyBytes, 0, bodyBytes.Length);
	req.GetRequestStream().Close();
}

HttpWebResponse resp;
try
{
	resp = (HttpWebResponse)req.GetResponse();
}
catch (WebException e)
{
	resp = (HttpWebResponse)e.Response;
}


POST XML Data submitted in request body:
XML
<RegionData xmlns="http://northwind.com/regions">
  <RegionDescription>New Region</RegionDescription>
  <RegionID>99</RegionID>
</RegionData>



I see that the request only reaches service operation in debug mode when all of the following is used:
1) [XmlSerializerFormat] on Service Contract
2) BodyStyle=WebMessageBodyStyle.Wrapped set on Service Operation
2) req.ContentType = null; in client call to service

However, although it reaches service operation, the objRegion shows as null.

I am not able to find out whats wrong or what is the right combination of attributes at either service contract, data contract, service implementation, app.config or client code that actually works, and if i missed anything.

Please help!
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900