Write a webservice method with both URI and DataContract class parameters

独自空忆成欢 提交于 2019-11-29 12:25:00

You want to keep same URI for both, GET and POST.

  1. 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.

  2. 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

mrtig

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!