i have a WCF rest service with one POST method that save members. the method take the member an Object parameter. i have "automaticFormatSelectionEnabled" turned on and i am able to specify the request Format "JSON or XML" from the client side and pass it to the service. the service will deal with the request based on the format accept header.
the idea is to have only one method for adding one member or multiple members. when i get the request Object from the client i check if its a member type or a list of member type, based on that i cast this Object explicitly to the appropriate type and pass it to the service layer to be validated and saved.
this method works very well when i am sending the member/list object as an XML but with JSON its not working, the object cannot be deserialized and even an explicit conversion does not work.
my code:
the interface
[ServiceKnownType(typeof(List<Member>))]
[ServiceKnownType(typeof(Member))]
[ServiceKnownType(typeof(object))]
[ServiceKnownType(typeof(Response))]
[WebInvoke(UriTemplate = "/Members", BodyStyle = WebMessageBodyStyle.Bare)]
object SetMembers(object members);
the service:
public object SetMembers(object members)
{
if (members.GetType() == typeof(Member))
{
return MemberService.SetMember((Member)members);
}
return MemberService.SetMembers((List<Member>)members);
}
client code
private static void AddMemberJSON()
{
//Create Member JSON
var memberJSON = "{\"BranchId\":\"c4e833c0-7675-4650-8d58-f64df87bb0f2\",\"FirstName\":\"Post\",\"LastName\":\"OMG\",\"MemberId\":\"c0aff7a7-bb7c-4f4e-ac89-0181a58afe12\"}";
//Create rest request
var request = new RestRequest("Members", Method.POST) {RequestFormat = DataFormat.Json};
request.AddParameter("application/json; charset=utf-8", memberJSON, ParameterType.RequestBody);
//Execute rest request
var response = _client.Execute(request);
}
No comments:
Post a Comment