I am trying to write a C# restful web service which returns the customer name when account number is passed as a parameter.
I have a customer class:
public class Customer_T
{
public string CustName { get; set; }
}
An interface class:
[ServiceContract(Namespace = "", Name = "CustomerInfoService")]
public interface CustomerInfo_I
{
[OperationContract]
Customer_T CustName(string accountno);
}
*Another class called CustomerInfo which implements the CustomerInfo_I interface:*
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class CustomerInfo : CustomerInfo_I
{
[WebInvoke(Method = "GET", UriTemplate = "customer/{accountno}", ResponseFormat = WebMessageFormat.Json)]
public Customer_T CustName(string accountno)
{
string custName = "";
CustNameByAccountNo custdb = new CustNameByAccountNo();
custName = custdb.getCustName(accountno).ToString();
if (custName.Equals("") == false)
{
return new Customer_T { CustName = custName };
}
else
{
return null; //This is where I want to change
}
}
}
Instead of returning null, I would like to return a string “InvalidAccNo”.
I did try it, but it gave me an error.
Cannot implicitly convert type 'string' to 'CustomerInfo.Service.Customer_T'
You won’t be able to return a string since your return type is defined as a
Customer_T. One option you might want to consider is to take a look at fault handling inside of WCF to return a fault to a user rather than repurposing a single object. Throwing the fault can be used in indicate that an invalid account number was specified.http://msdn.microsoft.com/en-us/library/ms733721.aspx
Also, your Customer class, you should mark the class with the
DataContractattribute and your data members withDataMemberin order to return complex types.