raj kiran

raj kiran

  • NA
  • 4
  • 22.5k

How to validate the request parameters of the WCF rest POST

Apr 28 2014 5:41 AM

I am new to WCF and I have written a WCF service which look like below

[OperationContract]

[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json,UriTemplate = "/Customer/CustomerDetails")]

SucessResponse SaveCustomerInfo(CustomerInfo objCustomerInfo);

public class CustomerInfo

{

public string FirstName { get; set; }

public string LastName { get; set; }

public decimal PrimaryPhone { get; set; }

public decimal SecondaryPhone { get; set; }

public string PrimaryEmailId { get; set; }

public string SecondaryEmailId { get; set; }

}

 

Now, I created a client application to consume the above service using HttpWebRequest

string URL = "http://localhost:22250/KMG/CustomerService.svc";

CustomerInfo objCustomerInfo = new CustomerInfo ();

{

objCustomerInfo.FirstName = "Raj";

objCustomerInfo.LastName = "Kiran";

objCustomerInfo.Email = "[email protected]";

objCustomerInfo.PrimaryPhone = 99999;

objCustomerInfo.SecondaryPhone = 99999;

};

jsonRequest = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(objCustomerInfo);

var datatoSend = Encoding.UTF8.GetBytes(jsonRequest);

myHttpWebRequest = (HttpWebRequest)WebRequest.Create(URL);

myHttpWebRequest.ContentType = "application/json";

myHttpWebRequest.ContentLength = datatoSend.Length;

myHttpWebRequest.Method = "POST";

myHttpWebRequest.GetRequestStream().Write(datatoSend, 0, datatoSend.Length);

myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();

Now the problem, I am facing is, when I pass, the request parameters like PrimaryPhone and SecondaryPhone a text value like “Demo” or “ABC” it is throwing a 400 Bad Request error, which is correct because we are making a bad request.

My question here is, in the above case, where instead of passing numeric value to PrimaryPhone, when a user pass text or any other wrong value, I want to send user a genric error message like “PrimaryPhone should be positive number”.

How can I achieve this?, because when I calling the service above with wrong values in debugging mode it is not even hitting the service, as soon as I reach this line below

myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
it is directly going to catch block and showing the 400 bad request error, it is not even going to service implementation class (SVC.cs).
In case of GET method i am able to handle it by checking the parameters in service implementation class, but in case of POST, i am unable to do it, as i am unable hit the service in debugging mode. I want to validate request parameters and send user a genric error message.

Please help me in the regard.


Answers (1)