0

I have a method which return a 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 it is correct it returns data like this:

{
companies: [
{
cono: "001",
name: "Company001"
}
]
}

but if request key is not correct I want to return an error code in json like this

{-100}

How can I change the return type of the method to Int or how can I return desired data in the above format

4

2 回答 2

0

将您的返回类型更改为这样的内容怎么样?

[DataContract]
public class Cono
{
    [DataMember(Order = 1)]
    public Companies[] companies;

    [DataMember(Order = 2)]
    public Error error;    
}

public class Error
{
    public int code;
    public string message;
}

然后,如果您有错误,companies将为 null 并且error将被设置。如果您没有错误,error则将为 nullcompanies并将被设置。

于 2013-05-02T16:12:14.980 回答
0

您可以将方法的返回类型更改为Stream( public Stream GetCompanies(string requestKey);) 并编写一个方法

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);
}

然后,在您的方法中,您可以将其用作

........
return ToJson(anyObject)
于 2013-05-02T16:15:31.050 回答