c# - Return Different JSON in WCF method on error -
i have method return class cono in json format
[datacontract] public class cono { [datamember(order = 1)] public companies[] companies; } public class companies { [datamember(order = 1)] public string cono; [datamember(order = 2)] public string name; } [webget(uritemplate = "getcompanies?requestkey={requestkey}", responseformat = webmessageformat.json)] public cono getcompanies(string requestkey);
this method first validate request key if correct returns data this:
{ companies: [ { cono: "001", name: "company001" } ] }
but if request key not correct want return error code in json this
{-100}
how can change return type of method int or how can return desired data in above format
you can change return type of method stream
(public stream getcompanies(string requestkey);
) , write method
static stream tojson(object o) { var result = jsonconvert.serializeobject(o); var data = encoding.utf8.getbytes(result); weboperationcontext.current.outgoingresponse.contenttype = "application/json; charset=utf-8"; weboperationcontext.current.outgoingresponse.contentlength = data.length; return new memorystream(data); }
then, in method, can use
........ return tojson(anyobject)
Comments
Post a Comment