How can I get a web service method to access parameters in the URI and complex POST data?
I have a web service method with some parameters in the URI:
You want to keep same URI for both, GET and POST.
When a GET method is called with parameters /api/{something}/{id}, then based on the id, it will return data to client that he/she can edit.
When editing is done, send that edited data back to server using POST method with same URI and Id as mentioned in GET request.
If it is so, then here is the solution:
To do so, create two methods with same UriTemplate but with different names.
[ServiceContract]
public interface IMyWebSvc
{
[OperationContract]
[WebGet(UriTemplate = "/api/{something}/{id}",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare)]
MyWebSvcRetObj GetData(string something, string id);
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "/api/{something}/{id}",
RequestFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare)]
string Update(MoreData IncomingData, string something, string id);
}
Now, what should be the format of JSON. It is easy. In your MoreData
class, override the ToString()
method.
public override string ToString()
{
JavaScriptSerializer js = new JavaScriptSerializer();
return js.Serialize(this);
}
The JavaScriptSerializer
is available in System.Web.Script.Serialization. Now, to check which JSON format your service will accept, make a dummy call to your web service method and hit a break point on object.ToString()
method.
MoreData md = new MoreData();
string jsonString = md.ToString(); // hit break point here.
When you hit break point, in jsonString
variable, you will have json that your service will accept. So, recommend your client to send JSON in that format.
So, you can specify as much as complex types in your MoreData
class.
I hope this will help you! Thanks
It looks like you are posting JSON data to your strongly typed webservice method.
This is somewhat tangential to this topic: How to pass strong-typed model as data param to jquery ajax post?
One solution is to accept a Json
object (the key-value pairs you mentioned) and deserialize into your MoreData
type.